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

I've already reviewed this answer, Jest documentation, and several GitHub threads:

Disable Jest setTimeout mock

Right now, the function inside the timeout doesn't run. How can I get Jest to pause its execution of the test for 15 seconds and then run the inner function?

Thanks!

3

3 Answers

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

or

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

A nice and clean way to do it (without callbacks) we can simply run an await and pass the res to setTimeout(res, XXX) like so:

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)
});
0
votes

setTimeout is now available through the jest object, and it will function as you expect: 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)
});

Note: If you attempt to set a timeout for 5000ms or more without the jest object, jest will error and let you know to use jest.setTimeout instead.