Mocha ASYNCHRONOUS CODE

ASYNCHRONOUS CODE

Testing asynchronous code with Mocha could not be simpler! Simply invoke the callback when your test is complete. By adding a callback (usually named done) to it(), Mocha will know that it should wait for this function to be called to complete the test.

describe(‘User’, function() {
describe(‘#save()’, function() {
it(‘should save without error’, function(done) {
var user = new User(‘Luna’);
user.save(function(err) {
if (err) done(err);
else done();
});
});
});
});
To make things even easier, the done() callback accepts an error, so we may use this directly:

describe(‘User’, function() {
describe(‘#save()’, function() {
it(‘should save without error’, function(done) {
var user = new User(‘Luna’);
user.save(done);
});
});
});
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:

beforeEach(function() {
return db.clear()
.then(function() {
return db.save([tobi, loki, jane]);
});
});

describe(‘#find()’, function() {
it(‘respond with matching records’, function() {
return db.find({ type: ‘User’ }).should.eventually.have.length(3);
});
});
The latter example uses Chai as Promised for fluent promise assertions.

In Mocha v3.0.0 and newer, returning a Promise and calling done() will result in an exception, as this is generally a mistake:

const assert = require(‘assert’);

it(‘should complete this test’, function (done) {
return new Promise(function (resolve) {
assert.ok(true);
resolve();
})
.then(done);
});
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.

Questions