Calvin Hu Calvin Hu - 4 months ago 26
Node.js Question

calling kriskowal type promise function in Mocha's before and after function

Hi folks so I'm writing Mocha test to test my Node.js server. The test just needs to check if a json file IO utility I wrote can correctly write files. One of the issues is that I'm not sure how I properly call an async function(which returns a kriskowal/q type promise) in the before function. I need to wait for the async function in the before section to finish before running the test case.

According to https://mochajs.org/#asynchronous-code, the before function needs to take a "done" callback for it to be waited until finish. But since my function returns a promise can I simply do the following to utilize the done function : ?

describe("test create/read/delete json file", function () {
before(function (done) {
fileHelper.writeJsonFile(mailTypeFile, json, {spaces: 2}).then(function () {
done();
}).catch(function (error) {
done(error);
})
});

after(function (done) {
fileHelper.deleteFile(mailTypeFile).then(function () {
done();
}).catch(function (error) {
done(error);
})
});

it('should create mailtype', function (done) {
fileHelper.readJsonFile(mailTypeFile).then(function (data) {
expect(data).to.have.property('required');
expect(data).to.have.property('properties');
done();
}).catch(function (error) {
done(error);
})
})
});


So I call done() if the promise resolves and done(err) if the promise rejects. Is it guaranteed to wait for the before() to finish ?

Answer

Since your functions return promises, you can just return the promise. Mocha will wait for the promise to be resolved or rejected before moving to the next thing. Do not declare done in the parameters of your anonymous functions you pass to it, before, after and do not call it.