javascript - 即使使用 sinon.useFakeTimer(),TimeOut 也不起作用

标签 javascript timer timeout mocha.js sinon

环境:Mocha、Sinon、node.js。为什么这个测试在超时时间为 5500ms 的情况下却在 8ms 内执行?也许我不明白计时器是什么?我的意思是,它应该中间执行,对吗?直到计时器结束才完成测试。

var   sinon     = require('sinon');
var   chai      = require('chai');

 expect = chai.expect;
 should = chai.should();
 assert = chai.assert;

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

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

it("should time out after 5000 ms", function() {
    var timedOut = false;
    setTimeout(function () {
        timedOut = true;
    }, 5000);

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

最佳答案

我找到了在 Mocha for node.js 中使用 setTimeOut 的方法。

// We need to pass the mocha's function 'done' that tells mocha to wait till this function is called
it('It should wait around 5 seconds', function(done){

    // We augment mocha's timeout to more than default 2000ms
    // we put more than the 5 seconds of setTimeout to asure us
    this.timeout(6 * 1000);

    setTimeout(function(){

        // tells mocha we are finished
        done();

    }, 5*1000);
});

这是 jasmine 中“等待”功能的替代品。

关于javascript - 即使使用 sinon.useFakeTimer(),TimeOut 也不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26995430/

相关文章:

javascript - FlexSlider 未捕获类型错误和引用错误

javascript - "return false"不停止回发到 Controller

c# - 在 WPF 窗口中显示正在运行的计时器

ios - 使用 Swift 4 在 WatchOS 中创建一个简单的计时器

c# - 数据库重新联机后连接请求超时

javascript - 动态更改 html select 元素的类

javascript - 在 JQuery 中捕获表单输入

java - 设置中断位不会使 Future.get() 抛出 TimeoutException

javascript - vue js Prop 重置计时器

error-handling - 尝试/除了不捕捉 future 的 TimeoutError