MCPcopy Index your code
hub / github.com/testing-library/react-hooks-testing-library / asyncUtils

Function asyncUtils

src/core/asyncUtils.ts:16–94  ·  view source on GitHub ↗
(act: Act, addResolver: (callback: () => void) => void)

Source from the content-addressed store, hash-verified

14const DEFAULT_TIMEOUT = 1000
15
16function asyncUtils(act: Act, addResolver: (callback: () => void) => void): AsyncUtils {
17 const wait = async (callback: () => boolean | void, { interval, timeout }: WaitOptions) => {
18 const checkResult = () => {
19 const callbackResult = callback()
20 return callbackResult ?? callbackResult === undefined
21 }
22
23 const timeoutSignal = createTimeoutController(timeout)
24
25 const waitForResult = async () => {
26 while (true) {
27 const intervalSignal = createTimeoutController(interval)
28 timeoutSignal.onTimeout(() => intervalSignal.cancel())
29
30 await intervalSignal.wrap(new Promise<void>(addResolver))
31
32 if (checkResult() || timeoutSignal.timedOut) {
33 return
34 }
35 }
36 }
37
38 if (!checkResult()) {
39 await act(() => timeoutSignal.wrap(waitForResult()))
40 }
41
42 return !timeoutSignal.timedOut
43 }
44
45 const waitFor = async (
46 callback: () => boolean | void,
47 { interval = DEFAULT_INTERVAL, timeout = DEFAULT_TIMEOUT }: WaitForOptions = {}
48 ) => {
49 const safeCallback = () => {
50 try {
51 return callback()
52 } catch (error: unknown) {
53 return false
54 }
55 }
56
57 const result = await wait(safeCallback, { interval, timeout })
58 if (!result && timeout) {
59 throw new TimeoutError(waitFor, timeout)
60 }
61 }
62
63 const waitForValueToChange = async (
64 selector: () => unknown,
65 { interval = DEFAULT_INTERVAL, timeout = DEFAULT_TIMEOUT }: WaitForValueToChangeOptions = {}
66 ) => {
67 const initialValue = selector()
68
69 const result = await wait(() => selector() !== initialValue, { interval, timeout })
70 if (!result && timeout) {
71 throw new TimeoutError(waitForValueToChange, timeout)
72 }
73 }

Callers 1

renderHookFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…