Jest setTimeout没有暂停测试

时间:2017-09-06 13:57:23

标签: javascript testing timer jest

it('has working hooks', async () => {
  setTimeout(() => {
    console.log("Why don't I run?")
    expect(true).toBe(true)
  }, 15000)

我已经回顾了这个答案,Jest文档和几个GitHub线程:

Disable Jest setTimeout mock

现在,超时内的函数不会运行。 如何让Jest暂停执行测试15秒然后运行内部函数?

谢谢!

3 个答案:

答案 0 :(得分:3)

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)
}

答案 1 :(得分:1)

一种不错的方法(无需回调),我们可以简单地运行await并将res传递给setTimeout(res, XXX),如下所示:

it('works with a setTimeout', async () => {
  // await 15000ms before continuing further
  await new Promise(res => setTimeout(res, 15000));

  // run your test
  expect(true).toBe(true)
});

答案 2 :(得分:0)

setTimeout 现在可通过 jest 对象使用,它会按您的预期运行:https://jestjs.io/docs/jest-object#misc

it('works with jest.setTimeout', async () => {
  // pause test example for 15 seconds
  jest.setTimeout(15000)

  // run your test
  expect(true).toBe(true)
});

注意:如果您尝试在没有 jest 对象的情况下设置 5000 毫秒或更长时间的超时,jest 会出错并通知您改用 jest.setTimeout。