2017-08-23 142 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