5

I know I can use jest.setTimeout() to set a custom timeout for a test. I'm doing this below. MINUTE has the value 60 * 1000.

Why isn't Jest applying my timeout?

    thrown: "Exceeded timeout of 5000 ms for a test.
    Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."

      13 |
      14 | describe(`integration with API provider`, () => {
    > 15 |   it(`works`, async () => {
         |   ^
      16 |     // Just in case network is slow.
      17 |     jest.setTimeout(1 * MINUTE);
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
  • 1
    _"This only affects **the test file** from which this function is called."_ - you're expected to call it from the file, not the test. Jest sets the timeout _before_ calling the function, you can't change it from inside. For a single test's timeout, you can pass a third argument to `it`/`test`. – jonrsharpe May 04 '22 at 16:04
  • @jonrsharpe Do you want to add this - in particular the 'for a single tests timeout' part - as an answer? – mikemaccana May 04 '22 at 16:07
  • Also related: https://stackoverflow.com/q/68811529/3001761. – jonrsharpe May 04 '22 at 16:47
  • Hah apparently I answered this before too . Feel free to mark as a dupe if you like. – mikemaccana May 04 '22 at 16:48

1 Answers1

10

As you've seen (and despite what's claimed elsewhere on SO), you cannot change a single test's timeout by calling jest.setTimeout from inside it. Note that the docs you quote state (emphasis mine):

This only affects the test file from which this function is called.

It's intended to be used at test discovery time, not execution time, to set the timeout for a given context. The timeout is set before the test callback is invoked, you can't change it once the test actually starts.

For a single test you can set the timeout by passing a third argument to the test/it function (or the various helpers defined on it), for example:

it("has a description", () => {
  // ...
}, 60_000);
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Link edit 'passing a third argument to the test/it function' was to describe what is being linked (the link demonstrates passing a third argument). Obviously you don't seem to like the change so I've left it as is. – mikemaccana May 04 '22 at 16:36
  • I've [fixed the jest docs to make them clearer](https://github.com/facebook/jest/pull/12809) – mikemaccana May 13 '22 at 12:53