2017-08-23 158 views
1

我正在学习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?由于

UPDATE

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 

UPDATE

感谢@Louis。设置useFakeTimers工作正常。

但我只是困惑。为什么在我的项目中,默认情况下useFakeTimers设置为true的现有测试没有问题?如果useFakeTimers设置为true,则承诺延迟不能用于sinonTest()

顺便说一下,当将sinon1.17.6更新为2.4.1时,我遇到了这个问题。 谢谢

回答

0

默认情况下,Sinon创建的沙箱具有其配置集,以便沙箱配置选项useFakeTimerstrue。 (在documentation page中搜索defaultConfig。)

这意味着在沙箱生效时,时钟似乎停止,蓝鸟的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()

默认useFakeTimerstrue,但除非你有一些代码取决于时钟向前移动至正常工作,不会造成问题。我有很多测试套件,在这些测试套件中使用了沙箱,并且我没有注意关闭假定时器,并且它们工作正常。假定时器通常不会阻止异步功能运行。例如,如果您在沙盒生效时执行fs.readFile,则它应该可以正常工作。它只影响依赖于时钟的功能,如setTimeout,setIntervalDate

Bluebird的delay方法受到影响,因为它的作用是calls setTimeout

+0

如果'{useFakeTimers:false}'set,'delay'不起作用? – BAE

+0

我把你的问题中的代码放在一个新的文件中,编辑添加第二个参数'{useFakeTimers:false}',安装所需的软件包并运行Mocha并运行。我得到了所有'console.log'输出,并且没有时间。它在我写回答之前做到了,现在它可以工作。你一定在做错事。 – Louis

+0

是的。它正在工作。你解决了我的几个问题。谢谢。但我只是困惑。为什么在我的项目中,没有设置'useFakeTimers'的现有测试没有问题? – BAE