Javascript asynchronous testing

Tue Feb 27 2018

While creating my current project, I had some functionality that involved timing and scheduling. I started writing my tests and got stuck with that object, as the tests simply didnt wait for my callbacks and simply ran through the code and exited.

This wasnt acceptable as the asynchronous calls were a major part of the functionality. After googling and browsing stackoverflow, I found this nice option on mocha.

You simply add the done variable to your it tests and the test will wait until you call the done callback (it will fail after 2 seconds if you dont do it).

You can see the code below that the asynchronous actions may fool you and not get tested as in the first example.

Make sure that all the code you write gets passed through!

Enjoy, and I really hope I save someone some time from his life 🙂

This test will succeed but will not check the whole test {#thistestwillsucceedbutwillnotcheckthewholetest}
//in mocha describe function

it("this is an asynchronous test", function(){  
    var tester = true;
    expect(tester).to.be.true;

    setTimeout(function() {
        //********************************
        // YOU WILL NEVER GET HERE....
        // THIS IS NOT TESTED
        //********************************
        tester = false;
        expect(tester).to.be.false;

      }, 1000);       
});
This test will succeed and will properly check the asynchronous action {#thistestwillsucceedandwillproperlychecktheasynchronousaction}
//in mocha describe function

it("this is an asynchronous test", function(done){  
    var tester = true;

    expect(tester).to.be.true;

    setTimeout(function() {
        tester = false;
        expect(tester).to.be.false;
        done();
    }, 1000);       
});