jest settimeout不暂停测试

问题描述 投票:0回答:4
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)) })

javascript testing timer jestjs
4个回答
46
投票
it('has working hooks', done => {
  setTimeout(() => {
    console.log("Why don't I run?")
    expect(true).toBe(true)
    done()
  }, 15000)
})

我们可以简单地运行一个
await

18
投票
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
:使用

0
投票

其他解决方案很有意义,但对我不起作用。在这种情况下,请考虑:

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.

.

-5
投票

注:如果您尝试在没有开玩笑对象的情况下设置5000ms或更多的超时,请带错误并告诉您使用jest.settimeout。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.