Sometimes, we want to fix async function in mocha before() is always finished before it() spec with JavaScript.
In this article, we’ll look at how to fix async function in mocha before() is always finished before it() spec with JavaScript.
How to fix async function in mocha before() is always finished before it() spec with JavaScript?
To fix async function in mocha before() is always finished before it() spec with JavaScript, we can return a promise in the before
callback.
For instance, we write
let a = 0;
before(() => {
return new Promise((resolve) => {
setTimeout(() => {
a = 1;
resolve();
}, 200);
});
});
it("a should be set to 1", () => {
assert(a === 1);
});
to call before
with a callback that returns a promise.
Then the it
callback should run after the promise in the before
callback is finished.
Conclusion
To fix async function in mocha before() is always finished before it() spec with JavaScript, we can return a promise in the before
callback.