我正在学习sinon。我的代码:
const bluebird = require('bluebird');
const sinon = require('sinon');
const sinonTest = require('sinon-test')(sinon);
sinon.test = sinonTest;
describe('xxx', function _test() {
this.timeout(2000);
it('should', sinon.test(function() {
return new bluebird.Promise( (resolve, reject) => {
try {
console.log('123');
resolve();
} catch ( err ) {
reject(err);
};
})
.then( () => console.log('456') )
.delay(100)
.then( () => console.log('789') )
.then(function() {
})
}));
});
输出:
xxx
123
456
为什么以上代码超时并停留在delay
?感谢
更新
const bluebird = require('bluebird');
const sinon = require('sinon');
const sinonTest = require('sinon-test')(sinon);
sinon.test = sinonTest;
describe('xxx', function _test() {
this.timeout(2000);
it('should', sinon.test(function() {
return bluebird
.delay(100)
.then( () => console.log('789') );
}));
});
输出:
Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves
更新
谢谢@Louis。设置useFakeTimers
可以正常工作。
但我很困惑。为什么在我的项目中,默认情况下useFakeTimers
设置为true的现有测试没有问题?如果useFakeTimers
设置为true,则无法在sinonTest()
中使用保证延迟?
顺便说一句,将sinon
从1.17.6
升级到2.4.1
时出现此问题。
感谢
答案 0 :(得分:1)
默认情况下,Sinon创建的沙箱的配置设置为沙盒配置选项useFakeTimers
为true
。 (在此documentation page中搜索defaultConfig
。)
这意味着当沙箱生效时,时钟似乎停止,而Bluebird的delay
永远不会解析。通过在配置第二个参数时传递第二个参数,告诉sinon-test
创建没有伪定时器的沙箱。第二个参数实际上是Sinon沙箱的配置对象:
const sinonTest = require('sinon-test')(sinon,
{ useFakeTimers: false });
我还没有尝试过,但是从眼睛看代码,如果你需要一些测试来使用假定时器而有些不使用假定时器,你看起来可以同时使用多个配置:
const sinonTest = require('sinon-test');
const wrapper = sinonTest(sinon, { useFakeTimers: false });
const wrapperWithTimers = sinonTest(sinon);
您只需使用正确的包装器来满足测试需求。
您添加了问题:
但我很困惑。为什么在我的项目中,默认情况下
中使用保证延迟useFakeTimers
设置为true的现有测试没有问题?如果useFakeTimers
设置为true,则无法在sinonTest()
?
默认情况下,useFakeTimers
为true
,但这不会导致问题,除非您的时钟上依赖的代码正常运行。我有很多测试套件,我使用沙箱,我没有注意关闭假定时器,他们工作正常。假定时器通常不会阻止异步功能运行。例如,如果在沙箱生效时执行fs.readFile
,它应该可以正常工作。它只会影响依赖于时钟的函数,例如setTimeout
,setInterval
和Date
。
Bluebird的delay
方法受到影响,因为它calls setTimeout
。