我認爲你正試圖測試你不應該做的事情。您的測試名稱建議您不要相信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();
}
}
我建議你也可以使用'sinon'與摩卡,它提供了你的方式間諜/嘲諷的東西,並多次操作對於這些情況timeout'的'例如:https://github.com/mochajs/摩卡/維基/ Spies – quirimmo