我正在学习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
更新
谢谢@路易斯。设置useFakeTimers
工作正常。
但是我只是感到困惑。为什么在我的项目中,useFakeTimers
默认情况下设置为true的现有测试没有问题?如果useFakeTimers
设置为true,则诺言延迟不能在sinonTest()
?中使用。
顺便说一下,sinon
从升级1.17.6
到时,我遇到了这个问题2.4.1
。谢谢
默认情况下,Sinon创建的沙箱具有其配置集,因此沙箱配置选项useFakeTimers
为true
。(defaultConfig
在此文档页面中搜索。)
这意味着在沙盒生效时,时钟似乎停止了,而Bluebird的时钟delay
永远都无法解析。您sinon-test
可以通过在配置时传递第二个参数来告诉您创建没有伪计时器的沙箱。该第二个参数实际上是锡诺沙箱的配置对象:
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
。
蓝鸟的delay
方法会受到影响,因为它会调用setTimeout
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句