Mocha runs all the tests in series, where each test can be synchronous or asynchronous. For a synchronous test, the test callback function should not accept any argument, as in the previous examples. But since Node.js doesn't block I/O operations, and we need to perform I/O operations for each of our tests (making at least an HTTP request to our server), our tests need to be asynchronous.
To make a test asynchronous, the test function should accept a callback function such as this:
it('tests something asynchronous', function(done) { doSomethingAsynchronous(function(err) { assert.ok(! err); done(); }); });
The done
callback function also accepts an error as the first argument, which means that instead of throwing an error, you can just call done
directly:
it('tests something asynchronous', function(done) {
doSomethingAsynchronous(function(err) {
done(err);
});
});
If you don't need to test the asynchronous function return value, you can pass the...