How to set waitFor options globally in React Testing Library?
Asked Answered
P

4

8

I was taking a look to the waitFor documentation and I was wondering if there is any way to configure it globally, for example in the jest.config or in the command used to launch the test suite?

I need to increase the timeout in every test and it is a bit annoying.

Peltier answered 5/7, 2021 at 5:27 Comment(0)
B
20

Per the documentation, the configuration option for the timeouts on the various asynchronous utilities is asyncUtilTimeout:

asyncUtilTimeout

The global timeout value in milliseconds used by waitFor utilities. Defaults to 1000ms.

You can configure this using the configure function, e.g. in a setupTests.js file:

import { configure } from "@testing-library/react";

configure({ asyncUtilTimeout: 5000 });
Beora answered 5/7, 2021 at 9:9 Comment(1)
Adding this line to my setupTests.js file fixed the waitFor tests that were passing locally, but failing in Github Actions (CI).Aerography
B
1

You could create a helper function, no?


export function wrappedWaitFor(cb, opts = {}) {
  waitFor(cb, { ...opts, timeout: 10000 });
}

Briefing answered 5/7, 2021 at 5:53 Comment(1)
I think it could be a valid workaround if it is not possible to configure it globalyPeltier
B
1

Adding to @jonrsharpe's answer https://mcmap.net/q/1251780/-how-to-set-waitfor-options-globally-in-react-testing-library

You can configure the timeout of async methods for @testing-library/react & @testing-library/dom in a setupTests.js / setupTests.ts file:

import { configure as configureReact } from "@testing-library/react";
import { configure as configureDom } from "@testing-library/dom";

configureReact({ asyncUtilTimeout: 5000 });
configureDom({ asyncUtilTimeout: 5000 });

But if you need to configure it for async methods of any other testing-library package then that needs to be configured for each async method, for ex.

waitFor(callback_func, { timeout: 5000 });

or create a helper function as suggested by @Baruch https://mcmap.net/q/1251780/-how-to-set-waitfor-options-globally-in-react-testing-library

Bowleg answered 12/4, 2022 at 6:38 Comment(0)
L
0

And a ts version of the answer @Baruch gave:

export async function waitForLonger<T>(
    callback: () => Promise<T> | T, 
    opts?: waitForOptions
): Promise<T> {
   return waitFor<T>(callback, { ...opts, timeout: 10000 });
}
Leventhal answered 8/3, 2024 at 8:21 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.