Asynchronous Code
By adding an argument (usually named done
) to it()
to a test callback, Mocha will know that it should wait for this function to be called to complete the test.
This callback accepts both an Error
instance (or subclass thereof) or a falsy value; anything else is invalid usage and throws an error (usually causing a failed test).
Alternatively, use the done()
callback directly (which will handle an error argument, if it exists):
Working with Promises
Alternately, instead of using the done()
callback, you may return a Promise.
This is useful if the APIs you are testing return promises instead of taking callbacks:
In Mocha v3.0.0 and newer, returning a Promise
and calling done()
will result in an exception, as this is generally a mistake:
The above test will fail with Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both. In versions older than v3.0.0, the call to
done()` is effectively ignored.
Using async / await
If your JS environment supports async / await, you can also write asynchronous tests like this:
Limitations of asynchronous callbacks
You can use all asynchronous callbacks (done
, Promise
, and async
/await
) in callbacks for it()
, before()
, after()
, beforeEach()
, afterEach()
) but not describe()
— it must be synchronous.
See #5046 for more information.
Synchronous Code
When testing synchronous code, omit the callback and Mocha will automatically continue on to the next test.