Testing asynchronous function with mocha

You have to specify the callback done as the argument to the function which is provided to mocha – in this case the it() function. Like so:

describe('api', function() {
    it('should load a user', function(done) { // added "done" as parameter
        assert.doesNotThrow(function() {
            doRequest(options, function(res) {
                assert.equal(res, '{Object ... }'); // will not fail assert.doesNotThrow
                done(); // call "done()" the parameter
            }, function(err) {
                if (err) throw err; // will fail the assert.doesNotThrow
                done(); // call "done()" the parameter
            });
        });
    });
});

Also, the signature of doRequest(options, callback) specifies two arguments though when you call it in the test you provide three.

Mocha probably couldn’t find the method doRequest(arg1,arg2,arg3).

Did it not provide some error output? Maybe you can change the mocha options to get more information.

EDIT :

andho is right, the second assert would be called in parallel to assert.doesNotThrow while it should only be called in the success callback.

I have fixed the example code.

EDIT 2:

Or, to simplify the error handling (see Dan M.’s comment):

describe('api', function() {
    it('should load a user', function(done) { // added "done" as parameter
        assert.doesNotThrow(function() {
            doRequest(options, function(res) {
                assert.equal(res, '{Object ... }'); // will not fail assert.doesNotThrow
                done(); // call "done()" the parameter
            }, done);
        });
    });
});

Leave a Comment