2017-10-15 80 views
1

考慮下面的函數,用摩卡如何測試一個在mocha內部使用setTimeout()的函數?

function helloAfter100ms(){ 
    setTimeout(function(){ 
    console.log('hello'); 
    },100) 
} 

測試代碼,

describe('#helloAfter100ms()',function(){ 
    it('console logs hello ONLY after 100ms',function(){ 
    // what should go here 
    }) 
}) 
+0

我建議你也可以使用'sinon'與摩卡,它提供了你的方式間諜/嘲諷的東西,並多次操作對於這些情況timeout'的'例如:https://github.com/mochajs/摩卡/維基/ Spies – quirimmo

回答

3

我認爲你正試圖測試你不應該做的事情。您的測試名稱建議您不要相信setTimeout函數僅在給定的超時後調用console.log

由於這不是你的代碼,你應該不應該單元測試它。此外,setTimeout是可能的東西,你可以肯定的正常工作。

那麼還有什麼需要測試的?您的代碼 - 稱爲setTimeout的代碼。 您可以確保正確調用setTimeout。

至於如何做到這一點 - 您可以使用兩個sinon功能。第一個是useFakeTimers,它可以讓你控制時鐘。第二個是間諜,你應該在console.log上使用它來確保它被調用。

describe('#helloAfter100ms()',function(){ 
    it('console logs hello ONLY after 100ms',function(){ 
    const clock = sinon.useFakeTimers(); 
    const logSpy = sinon.spy(console, 'log'); 
    helloAfter100ms(); 
    expect(logSpy).to.not.have.been.called; 
    clock.tick(100); 
    expect(logSpy).to.have.been.calledOnce; 
    logSpy.restore(); 
    clock.restore(); 
    } 
} 
0

更新:像這樣:

describe('helloAfter100ms', function(){ 
    it('console logs hello ONLY after 100ms', function(done){ 
     setTimeout(function(){ 
      console.log('hello.'); 
      done(); 
     }, 100) 
    }) 
}) 

參考:https://mochajs.org/#asynchronous-code

+0

如果您再次調用'console.log',而不是在其上創建一個間諜,並檢查它是否已用正確的參數調用 – quirimmo

+0

@quirimmo,那麼這不是測試! –

+0

抱歉挑剔,通過調用'done'完成異步的概念是完全完美的。但是如果你想測試3秒後是否調用了'console.log',你需要在該方法上創建一個間諜,並檢查該方法是否被調用了正確的參數。這並不意味着再次調用'console.log'。 但是,'done'的邏輯完全是完美的。 – quirimmo

相關問題