gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 10:54:19 27 4
gpt4 key购买 nike

环境: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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com