如何在 Mocha 测试中模拟时间的流逝,以便调用 setTimeout 回调? [英] How can I simulate the passing of time in Mocha tests so that setTimeout callbacks are called?
问题描述
为了执行周期性任务,我需要测试依赖于 setTimeout 的 JavaScript 代码.如何从我的 Mocha 测试中模拟时间的流逝,以便调用 setTimeout 回调?
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?
我基本上要求类似于 Jasmine 的模拟时钟 的功能,它允许您将 JavaScript 时间提前若干滴答声.
I am basically asking for functionality similar to Jasmine's Mock Clock, which allows you to advance JavaScript time by a number of ticks.
推荐答案
我发现 Sinon.JS 支持通过 sinon.useFakeTimers 操作 JavaScript 时钟,如其 假计时器 文档.这是完美的,因为我已经将 Sinon 用于模拟目的,而且我想 Mocha 本身不支持这一点是有道理的,因为它更多地属于模拟库的领域.
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.
这是一个使用 Mocha/Chai/Sinon 的示例:
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;
});
这篇关于如何在 Mocha 测试中模拟时间的流逝,以便调用 setTimeout 回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!