Jest setTimeout 不暂停测试

新手上路,请多包涵
it('has working hooks', async () => {
  setTimeout(() => {
    console.log("Why don't I run?")
    expect(true).toBe(true)
  }, 15000)

我已经查看了这个答案、Jest 文档和几个 GitHub 线程:

禁用 Jest setTimeout 模拟

现在,超时内的函数没有运行。我怎样才能让 Jest 暂停执行测试 15 秒,然后运行内部函数?

谢谢!

原文由 Nick 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 741
2 个回答
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)
})

原文由 Ron 发布,翻译遵循 CC BY-SA 4.0 许可协议

一个漂亮而干净的方法(没有回调)我们可以简单地运行 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)
});

原文由 Mark Pieszak - Trilon.io 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题