Search code examples
javascriptnode.jsmocha.jsgulp-mocha

Writing Mocha Test for Async functions which uses setTimeout()


Somehow I'm not able to write Mocha JS test for a relatively very simple function. The JavaScript Source file looks like this

exports.cb = function() {
    console.log("The function is called after 3 seconds");
}

exports.testfn = function(cb) {
  setTimeout(cb, 3000);
}

And the test code is written as

describe('Main Test', function(){
  it('A callback Tests', function(done){
    asn.testfn(asn.cb);
    done();
  });
});

I'm encountering 2 problems.

    1. The test code ends immediately with done()
    1. If I don't call done(), then the function is called but tests fails because it expected to call done() for async functions

I've looked into documentations but not sure how this can be done.

I can write tests using promises and it works fine. But for the scenarios where we need to use setTimeout, how shall it be done?


Solution

  • Assuming what you're trying to test is testfn, you wouldn't use cb, you'd use a callback in the test; see comments:

    describe('Main Test', function(){
      it('testfn calls the function after three seconds', function(done){
        // Remember the start time
        var start = Date.now();
        // Schedule callback
        asn.testfn(function() {
            // Has it been at least three seconds?
            if (Date.now() - start < 3000) {
                // No, trigger an error
            } else {
                // Yes, all's good!
                done();
            }
        });
      });
    });
    

    If you want to call asn.cb for some reason, you'd do it in the anonymous function above, but if you want to test asn.cb, you should do that serparately from testing asn.testfn.