Sinon clock.tick doesn#39;t advance time for setTimeout(Sinon clock.tick不会提前setTimeout的时间)
本文介绍了Sinon clock.tick不会提前setTimeout的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在为async
函数编写一个测试,该函数执行一系列任务,并在执行更多任务之前等待60秒。我正在尝试使用sinon.useFakeTimers()
跳过这60秒,以便可以在延迟后测试逻辑。
foo.js
module.exports.foo = async f => {
// ... more code ...
await new Promise((resolve, reject) => {
setTimeout(resolve, 60000);
});
// ... more code ...
f();
// ... more code ...
};
test-foo.js
const sinon = require('sinon');
const expect = require('chai').expect;
const { foo } = require('./foo');
describe('Module Foo ', function() {
it('call function after 1 minute', function() {
var clock = sinon.useFakeTimers();
const bar = sinon.stub();
foo(bar);
expect(bar.called).to.be.false;
clock.tick(100000);
expect(bar.called).to.be.true; // this one fails
});
});
我尝试将sinon.useFakeTimers();
放在其他各种位置,但承诺未解析,并且我传递给foo
的存根未被调用。
推荐答案
将您的测试函数async
和await
设置为Promise
之后解析的Promise
,以便在foo
中await
排队的Promise
回调有机会在执行断言之前运行:
const sinon = require('sinon');
const expect = require('chai').expect;
const { foo } = require('./foo');
describe('Module Foo ', function() {
it('call function after 1 minute', async function() { // <= async test function
var clock = sinon.useFakeTimers();
const bar = sinon.stub();
foo(bar);
expect(bar.called).to.be.false; // Success!
clock.tick(100000);
await Promise.resolve(); // <= give queued Promise callbacks a chance to run
expect(bar.called).to.be.true; // Success!
});
});
有关完整的详细信息,请参阅my answer here,其中使用Jest
和Jest
timer mocks,但概念是相同的,也适用于Mocha
和Sinon
fake timers。
这篇关于Sinon clock.tick不会提前setTimeout的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:Sinon clock.tick不会提前setTimeout的时间
基础教程推荐
猜你喜欢
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 动态更新多个选择框 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06