Testing with Mocha – 3. Testing asynchronous code

Published at: 2021-04-14 08:23:02

In JavaScript we often write asynchronous code, for example ajax calls, database operations etc. When testing our code we want to be able to test this asynchronous parts of our code as well. Let’s see how we can achieve this when testing with Mocha.

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.

See the Pen Testing with Mocha – Example 3.1 by Daniel Werner (@daniel-werner-the-decoder) on CodePen.

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.

See the Pen bGgvJYg by Daniel Werner (@daniel-werner-the-decoder) on CodePen.

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.

See the Pen QWdmXBb by Daniel Werner (@daniel-werner-the-decoder) on CodePen.

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();