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;
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…