6.5 Testing Asynchronous Code

Sample Asynchronous Function

module.exports.asyncAdd = (a, b, callback) => {
setTimeout(() => {
callback(a + b);
}, 1000);
}

Problem Analysis

it('should async add two numbers', () => {
utils.asyncAdd(4, 3, (sum) => {
expect(sum).toBe(7).toBeA('number');
})
})

The above testing suite will pass no matter whether toBe(7) or not. This passes because we have an asynchronous action before asynchronous callback is run. The Mocha receives no throw, then it assumes this test is okay.

it('should async add two numbers', (done) => {
utils.asyncAdd(4, 3, (sum) => {
expect(sum).toBe(7).toBeA('number');
done();
});
});

This done is an obstacle such that if done is not executed, the testing will not continue. By the time done is run, the test case should have come out.

Exercise:
Create an asynchronous version of square. Create an asynchronous testing suite to test it.

module.exports.asyncSquare = (x, callback) => {
setTimeout(() => {
callback(x * x);
}, 1000);
};