如何模拟Mocha测试中的时间流逝,以便调用setTimeout回调? [英] How can I simulate the passing of time in Mocha tests so that setTimeout callbacks are called?

查看:84
本文介绍了如何模拟Mocha测试中的时间流逝,以便调用setTimeout回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我基本上要求的功能类似于Jasmine的模拟时钟,它允许您将JavaScript时间推进许多刻度。

解决方案

我发现Sinon.JS支持通过sinon.useFakeTimers操作JavaScript时钟,如假定时器文档。这是完美的,因为我已经将Sinon用于嘲弄目的,我想Mocha本身不支持这一点,因为它更像是一个模拟库。



<这是一个使用Mocha / Chai / Sinon的例子:

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

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

it(应该在500 ms后超时,function(){
var timedOut = false;
setTimeout(function(){
timedOut = true;
},500);

timedOut.should.be.false;
clock.tick(510);
timedOut.should.be.true;
});


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.

解决方案

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

这篇关于如何模拟Mocha测试中的时间流逝,以便调用setTimeout回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆