javascript 如何在 Mocha 测试中模拟时间的流逝,以便调用 setTimeout 回调?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17446064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:22:21  来源:igfitidea点击:

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

javascriptmockingbddmocha

提问by aknuds1

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

我需要测试依赖于setTimeout 的JavaScript 代码以执行周期性任务。我如何从我的 Mocha 测试中模拟时间的流逝,以便调用 setTimeout 回调?

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

我基本上要求类似于Jasmine 的 Mock Clock 的功能,它允许您将 JavaScript 时间提前一些滴答声。

回答by aknuds1

I found out that Sinon.JS has support for manipulating the JavaScript clock, via sinon.useFakeTimers, as described in its Fake Timersdocumentation. 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.

我发现 Sinon.JS 支持通过 sinon.useFakeTimers 操作 JavaScript 时钟,如其Fake Timers文档中所述。这是完美的,因为我已经将 Sinon 用于模拟目的,我想 Mocha 本身不支持这一点是有道理的,因为它更多地属于模拟库的领域。

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

下面是一个使用 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;
});