Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I simulate the passing of time in Mocha tests so that setTimeout callbacks are called?

I need to test JavaScript code that relies on setTimeout in order to perform periodic tasks. How can I from my Mocha tests simulate the passing of time so that setTimeout callbacks gets called?

I am basically asking for functionality similar to Jasmine's Mock Clock, which allows you to advance JavaScript time by a number of ticks.

like image 415
aknuds1 Avatar asked Jul 03 '13 10:07

aknuds1


1 Answers

I found out that Sinon.JS has support for manipulating the JavaScript clock, via sinon.useFakeTimers, as described in its Fake Timers documentation. This is perfect since I already use Sinon for mocking purposes, and I guess it makes sense that Mocha itself doesn't support this as it's more in the domain of a mocking library.

Here's an example employing Mocha/Chai/Sinon:

var clock;
beforeEach(function () {
     clock = sinon.useFakeTimers();
 });

afterEach(function () {
    clock.restore();
});

it("should time out after 500 ms", function() {
    var timedOut = false;
    setTimeout(function () {
        timedOut = true;
    }, 500);

    timedOut.should.be.false;
    clock.tick(510);
    timedOut.should.be.true;
});
like image 69
aknuds1 Avatar answered Oct 18 '22 21:10

aknuds1