it('has working hooks', async () => {
setTimeout(() => {
console.log("Why don't I run?")
expect(true).toBe(true)
}, 15000)
我已经审查了此答案,开玩笑的文档和几个github线程:tosable Jest settimeout模拟
现在,超时内部的功能无法运行。 我如何开玩笑地暂停其对测试的执行15秒,然后运行内部功能? thanks!
it('has working hooks', async () => {
await new Promise(res => setTimeout(() => {
console.log("Why don't I run?")
expect(true).toBe(true)
res()
}, 15000))
})
it('has working hooks', done => {
setTimeout(() => {
console.log("Why don't I run?")
expect(true).toBe(true)
done()
}, 15000)
})
我们可以简单地运行一个
await
res
传递给
setTimeout(res, XXX)
这样的好方法(无回调)。
it('works with await Promise and setTimeout', async () => {
// await 15000ms before continuing further
await new Promise(res => setTimeout(res, 15000));
// run your test
expect(true).toBe(true)
});
tldr:使用
其他解决方案很有意义,但对我不起作用。在这种情况下,请考虑:
function toBeTested(){
setTimeout(() => { /* do stuff later */}, 500);
}
it('does stuff later' () =>{
toBeTested();
jest.advanceTimersByTime(600);
expect(/* things to be done */)
});
docs:https://jestjs.io/docs/timer-mocks#advance-timers-bytime
现在可以通过嘲笑对象获得settimeout,它将按照您的期望运行:https://jestjs.io/docs/jest-object#misc.
.