Test async code using done() with Mocha

When testing asynchronous code in Mocha, we need to be sure that we are letting Mocha know so it can handle the test case correctly.

Setting up and tearing down tests

Mocha gives us the ability to set up the environment for one or more specific tests within it() one time using before(), and before each individual test using beforeEach().

It also gives us the ability to do tear downs with after() and afterEach().

Using done() to handle async tests

In this example, we are setting up the value of var foo and then checking its value in the test.

The first test totally fails because we never let Mocha know that we are testing an async call. it gets called before setTimeout() completes, so the value of foo doesn't get set to true in time.

To do so, in the second test case, we pass done into the function. Mocha gives us 2 seconds to either complete a test, or call done();
If neither happens, Mocha will give us a timeout error.

mocha.setup("bdd");  
expect = chai.expect;

describe("this one won't work", function(){  
    var foo = false;
    before(function(){
        // async call using setTimeout
        setTimeout(function(){
            foo = true;
        }, 1000);
    });

    it("should fail", function(){
        expect(foo).equals(true);
    });
});

describe("this one will work", function(){  
    var foo = false;
    before(function(done){
        setTimeout(function(){
            foo = true;
            done();
        }, 1000);
    });
    it("should pass", function(){
        expect(foo).equals(true);
    });
});

mocha.run();

Run the above example on JSFiddle