0

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 ?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

But since my promise is a Q promise which follows a then()..catch()..done() format which is different from other common promise syntax, is it still allow to return such a promise inside before?
Mocha is not going to call the promise's .done() for you. What this means is that if there's an error in Mocha's rejection handler, then the error won't be caught. However, this would mean that Mocha is buggy. I don't write my tests with the assumption that Mocha is not running correctly and I don't think it is wise to do so because there's really no end to the number of ways in which Mocha could fail to run correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.