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的时间


猜你喜欢
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Fetch API 如何获取响应体? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01