Skip to content

Commit 90b6115

Browse files
committed
base waitFor on RTL implementation
1 parent 1928ec5 commit 90b6115

File tree

1 file changed

+144
-25
lines changed

1 file changed

+144
-25
lines changed

src/waitFor.js

Lines changed: 144 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// @flow
2+
/* globals jest */
23

34
import * as React from 'react';
45
import act from './act';
@@ -7,9 +8,14 @@ import {
78
throwRemovedFunctionError,
89
copyStackTrace,
910
} from './helpers/errors';
10-
import { setTimeout } from './helpers/getTimerFuncs';
11+
import {
12+
setTimeout,
13+
clearTimeout,
14+
setImmediate,
15+
jestFakeTimersAreEnabled,
16+
} from './helpers/timers';
1117

12-
const DEFAULT_TIMEOUT = 4500;
18+
const DEFAULT_TIMEOUT = 1000;
1319
const DEFAULT_INTERVAL = 50;
1420

1521
function checkReactVersionAtLeast(major: number, minor: number): boolean {
@@ -22,56 +28,169 @@ function checkReactVersionAtLeast(major: number, minor: number): boolean {
2228
export type WaitForOptions = {
2329
timeout?: number,
2430
interval?: number,
31+
stackTraceError?: ErrorWithStack,
2532
};
2633

2734
function waitForInternal<T>(
2835
expectation: () => T,
29-
options?: WaitForOptions
36+
{
37+
timeout = DEFAULT_TIMEOUT,
38+
interval = DEFAULT_INTERVAL,
39+
stackTraceError,
40+
}: WaitForOptions
3041
): Promise<T> {
31-
const timeout = options?.timeout ?? DEFAULT_TIMEOUT;
32-
let interval = options?.interval ?? DEFAULT_INTERVAL;
33-
// Being able to display a useful stack trace requires generating it before doing anything async
34-
const stackTraceError = new ErrorWithStack('STACK_TRACE_ERROR', waitFor);
42+
if (typeof expectation !== 'function') {
43+
throw new TypeError('Received `expectation` arg must be a function');
44+
}
45+
46+
// eslint-disable-next-line no-async-promise-executor
47+
return new Promise(async (resolve, reject) => {
48+
let lastError, intervalId;
49+
let finished = false;
50+
let promiseStatus = 'idle';
51+
52+
const overallTimeoutTimer = setTimeout(handleTimeout, timeout);
3553

36-
if (interval < 1) interval = 1;
37-
const maxTries = Math.ceil(timeout / interval);
38-
let tries = 0;
54+
const usingFakeTimers = jestFakeTimersAreEnabled();
55+
if (usingFakeTimers) {
56+
checkExpectation();
57+
// this is a dangerous rule to disable because it could lead to an
58+
// infinite loop. However, eslint isn't smart enough to know that we're
59+
// setting finished inside `onDone` which will be called when we're done
60+
// waiting or when we've timed out.
61+
// eslint-disable-next-line no-unmodified-loop-condition
62+
while (!finished) {
63+
if (!jestFakeTimersAreEnabled()) {
64+
const error = new Error(
65+
`Changed from using fake timers to real timers while using waitFor. This is not allowed and will result in very strange behavior. Please ensure you're awaiting all async things your test is doing before changing to real timers. For more info, please go to https://github.com/testing-library/dom-testing-library/issues/830`
66+
);
67+
if (stackTraceError) {
68+
copyStackTrace(error, stackTraceError);
69+
}
70+
reject(error);
71+
return;
72+
}
73+
// we *could* (maybe should?) use `advanceTimersToNextTimer` but it's
74+
// possible that could make this loop go on forever if someone is using
75+
// third party code that's setting up recursive timers so rapidly that
76+
// the user's timer's don't get a chance to resolve. So we'll advance
77+
// by an interval instead. (We have a test for this case).
78+
jest.advanceTimersByTime(interval);
79+
80+
// It's really important that checkExpectation is run *before* we flush
81+
// in-flight promises. To be honest, I'm not sure why, and I can't quite
82+
// think of a way to reproduce the problem in a test, but I spent
83+
// an entire day banging my head against a wall on this.
84+
checkExpectation();
85+
86+
// In this rare case, we *need* to wait for in-flight promises
87+
// to resolve before continuing. We don't need to take advantage
88+
// of parallelization so we're fine.
89+
// https://stackoverflow.com/a/59243586/971592
90+
// eslint-disable-next-line no-await-in-loop
91+
await new Promise((resolve) => setImmediate(resolve));
92+
}
93+
} else {
94+
intervalId = setInterval(checkRealTimersCallback, interval);
95+
checkExpectation();
96+
}
97+
98+
function onDone(error, result) {
99+
finished = true;
100+
clearTimeout(overallTimeoutTimer);
101+
102+
if (!usingFakeTimers) {
103+
clearInterval(intervalId);
104+
}
39105

40-
return new Promise((resolve, reject) => {
41-
const rejectOrRerun = (error) => {
42-
if (tries > maxTries) {
43-
copyStackTrace(error, stackTraceError);
106+
if (error) {
44107
reject(error);
45-
return;
108+
} else {
109+
// $FlowIgnore[incompatible-return] error and result are mutually exclusive
110+
resolve(result);
111+
}
112+
}
113+
114+
function checkRealTimersCallback() {
115+
if (jestFakeTimersAreEnabled()) {
116+
const error = new Error(
117+
`Changed from using real timers to fake timers while using waitFor. This is not allowed and will result in very strange behavior. Please ensure you're awaiting all async things your test is doing before changing to fake timers. For more info, please go to https://github.com/testing-library/dom-testing-library/issues/830`
118+
);
119+
if (stackTraceError) {
120+
copyStackTrace(error, stackTraceError);
121+
}
122+
return reject(error);
123+
} else {
124+
return checkExpectation();
46125
}
47-
setTimeout(runExpectation, interval);
48-
};
49-
function runExpectation() {
50-
tries += 1;
126+
}
127+
128+
function checkExpectation() {
129+
if (promiseStatus === 'pending') return;
51130
try {
52-
const result = Promise.resolve(expectation());
53-
resolve(result);
131+
const result = expectation();
132+
133+
// $FlowIgnore[incompatible-type]
134+
if (typeof result?.then === 'function') {
135+
promiseStatus = 'pending';
136+
// eslint-disable-next-line promise/catch-or-return
137+
result.then(
138+
(resolvedValue) => {
139+
promiseStatus = 'resolved';
140+
onDone(null, resolvedValue);
141+
return;
142+
},
143+
(rejectedValue) => {
144+
promiseStatus = 'rejected';
145+
lastError = rejectedValue;
146+
return;
147+
}
148+
);
149+
} else {
150+
onDone(null, result);
151+
}
152+
// If `callback` throws, wait for the next mutation, interval, or timeout.
54153
} catch (error) {
55-
rejectOrRerun(error);
154+
// Save the most recent callback error to reject the promise with it in the event of a timeout
155+
lastError = error;
156+
}
157+
}
158+
159+
function handleTimeout() {
160+
let error;
161+
if (lastError) {
162+
error = lastError;
163+
if (stackTraceError) {
164+
copyStackTrace(error, stackTraceError);
165+
}
166+
} else {
167+
error = new Error('Timed out in waitFor.');
168+
if (stackTraceError) {
169+
copyStackTrace(error, stackTraceError);
170+
}
56171
}
172+
onDone(error, null);
57173
}
58-
setTimeout(runExpectation, 0);
59174
});
60175
}
61176

62177
export default async function waitFor<T>(
63178
expectation: () => T,
64179
options?: WaitForOptions
65180
): Promise<T> {
181+
// Being able to display a useful stack trace requires generating it before doing anything async
182+
const stackTraceError = new ErrorWithStack('STACK_TRACE_ERROR', waitFor);
183+
const optionsWithStackTrace = { stackTraceError, ...options };
184+
66185
if (!checkReactVersionAtLeast(16, 9)) {
67-
return waitForInternal(expectation, options);
186+
return waitForInternal(expectation, optionsWithStackTrace);
68187
}
69188

70189
let result: T;
71190

72191
//$FlowFixMe: `act` has incorrect flow typing
73192
await act(async () => {
74-
result = await waitForInternal(expectation, options);
193+
result = await waitForInternal(expectation, optionsWithStackTrace);
75194
});
76195

77196
//$FlowFixMe: either we have result or `waitFor` threw error

0 commit comments

Comments
 (0)