How to test async code in Mocha
In this article, you will learn how to test async code by using Mocha.
Mocha is a JavaScript test framework that runs on Nodejs as well as in Browser. It is an open-source testing framework for JavaScript. In mocha, you can test your asynchronous JavaScript code.
Let’s build an async function for the test with mocha. Suppose you have an async function that has two parameters that expect two numbers and return a resolved promise with the summation of two numbers.
async function sum(a, b) {
return Promise.resolve(a + b);
}
Now let’s test this async function with mocha. Follow the below example:
describe('#sum()', () => {
it('Should return the sum of 5 + 5 = 10', async () => {
const result = await add(5, 5)
results.to.equal(10);
});
The test case will pass as it will find that 5 + 5 = 10 but if we change the number the test case will fail.
Let’s take our knowledge one step in advance. we will test callbacks using done() for an asynchronous function that makes an HTTP request using Axios. See the example:
const axios = require('axios');
function get(url, callBack) {
return axios.get(url);
}
describe('get()', function() {
it('Successfully works', function(done) {
get('<http://dummytest.org/get?age=22>') // Dummy link
.then(res => {
assert.equal(res.data.args.age, 22);
done();
})
.catch(err => done(err));
});
});
Here, when you call done() and pass no arguments, mocha will consider the test as succeeded and when you pass a parameter into it mocha will take that parameter as an error.
Important: You have to keep one thing in mind that you have to call done() otherwise will get an mocha time-out error**.**