Ahmed-Anas Ahmed-Anas - 6 months ago 40
Node.js Question

node mocha async hooks not working?

Ok so I'm obviously new to mocha. From my understanding after reading the docs and googling this should work but it isn't:

describe("Check before", function(){

var beforeCalled = false;
before(function(){
setTimeout(function() {
beforeCalled = true;
done();
}, 150);
});

it("should run after before called", function(){
expect(beforeCalled).to.equal(true);
})
})


the
it
part doesn't wait for 'before' to finish and is called. Maybe I read the docs wrong or I'm missing something, not sure.

Any insight would be helpful.

Answer

The done callback must be in the function signature for mocha to wait.

before(function(done){
    setTimeout(function() {
        beforeCalled = true;
        done();
    }, 150);
});

I've got into the habit of always using done when there are mixed synchronous and async tests. Mocha can finish as if no tests have failed if you forget one async done on an it.

Comments