We're now ready to get back to our original task – writing unit tests for our Create User request handler! You should have enough understanding to implement the unit tests for the handler yourself, but we'd like to first give you some hints with regards to promises.
If the function we are testing perform asynchronous operations, there's no guarantee that the asynchronous operations would complete before our assertion code is run. For instance, if our create engine function is actually very slow to resolve, like so:
function createUser() {
aVerySlowCreate()
.then((result) => {
res.status(201);
});
}
Then the following test would fail:
describe("When create resolves with the new user's ID", function () {
beforeEach(function () {
createUser(req, res, db, create, ValidationError);
});
it('should call res.status() once', function () {
assert(res.status.calledOnce);
});
});
Mocha can deal with asynchronous code in two ways – using callbacks or promises. Since we'd generally avoid using callbacks, let's focus on working with promises. In Mocha, if we return a promise in the preceding beforeEach block, Mocha will wait for the promise to settle before running the relevant describe and it blocks. Therefore, when writing functions that involve asynchronous operations, we should always return a promise. Not only does it make the function easier to test, but it also allows you to chain multiple promises together should you have that need in the future.
Therefore, we must update our createUser function to a promise:
function createUser(req, res, db, create, ValidationError) {
return create(req, db)
...
}
Then, make sure that all of our beforeEach blocks also return a promise:
beforeEach(function () {
create = generateCreateStubs.success();
return createUser(req, res, db, create, ValidationError);
});