Sinon clock.tick doesn#39;t advance time for 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和Jesttimer mocks,但概念是相同的,也适用于Mocha和Sinonfake timers。
这篇关于Sinon clock.tick不会提前setTimeout的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Sinon clock.tick不会提前setTimeout的时间
基础教程推荐
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
