Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...