Asynchronous code with callbacks
For testing async code which uses callbacks we can use Mocha’s
done function. When passing
done in the test Mocha knows that it should wait for that callback to be called. Let’s see and example. Let’s add a save method to our collection, which will operate asynchronously.
Asynchronous code with Promises
If our code use promises instead of callback we can use doesNotReject assertion. Note: when testing promises do not use the
done callback. Let’s see and example how to test promises. We’ll “reimplement” the save method of our collection to use promises.
Important: When asserting promises, you should return the result of the assertion for Mocha to pick them up. Otherwise you’d in case when test should not pass, it passes, but you’d get an error.
Asynchronous code with async/await
If our code uses async/await, we can test it easily with Mocha. Let’s rewrite the previous example from using promises to use async/await.
As you can notice, we’ve added the async keyword to the save method, and when calling the method we use the await to wait for the asynchronous call result.
let result = await collection.save();
Check out all posts in the series Testing with Mocha.