【问题标题】:TimeOut doesn't work, even with sinon.useFakeTimer()TimeOut 不起作用,即使使用 sinon.useFakeTimer()
【发布时间】:2015-01-15 16:58:21
【问题描述】:

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

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

【问题讨论】:

  • sinon.useFakeTimers() 将全局 setTimeout 函数替换为一个版本,该版本在假时钟超过计时器的超时值时同步(立即)运行其回调。这就是为什么测试运行得很快。这是一件好事,您不希望您的单元测试每次测试花费 5 秒。

标签: javascript timer timeout mocha.js sinon


【解决方案1】:

我找到了在 Mocha 中为 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 中“等待”功能的替代品。

【讨论】:

    猜你喜欢
    • 2018-12-24
    • 1970-01-01
    • 2011-12-27
    • 2018-12-06
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多