Skip to content

Commit e28f28c

Browse files
committed
New internal testing helpers: waitFor, waitForAll
Over the years, we've gradually aligned on a set of best practices for for testing concurrent React features in this repo. The default in most cases is to use `act`, the same as you would do when testing a real React app. However, because we're testing React itself, as opposed to an app that uses React, our internal tests sometimes need to make assertions on intermediate states that `act` intentionally disallows. For those cases, we built a custom set of Jest assertion matchers that provide greater control over the concurrent work queue. It works by mocking the Scheduler package. (When we eventually migrate to using native postTask, it would probably work by stubbing that instead.) A problem with these helpers that we recently discovered is, because they are synchronous function calls, they aren't sufficient if the work you need to flush is scheduled in a microtask — we don't control the microtask queue, and can't mock it. `act` addresses this problem by encouraging you to await the result of the `act` call. (It's not currently required to await, but in future versions of React it likely will be.) It will then continue flushing work until both the microtask queue and the Scheduler queue is exhausted. We can follow a similar strategy for our custom test helpers, by replacing the current set of synchronous helpers with a corresponding set of async ones: - `expect(Scheduler).toFlushAndYield(log)` -> `await waitForAll(log)` - `expect(Scheduler).toFlushAndYieldThrough(log)` -> `await waitFor(log)` - `expect(Scheduler).toFlushUntilNextPaint(log)` -> `await waitForPaint(log)` These APIs are inspired by the existing best practice for writing e2e React tests. Rather than mock all task queues, in an e2e test you set up a timer loop and wait for the UI to match an expecte condition. Although we are mocking _some_ of the task queues in our tests, the general principle still holds: it makes it less likely that our tests will diverge from real world behavior in an actual browser. In this commit, I've implemented the new testing helpers and converted one of the Suspense tests to use them. In subsequent steps, I'll codemod the rest of our test suite.
1 parent c600974 commit e28f28c

File tree

4 files changed

+143
-9
lines changed

4 files changed

+143
-9
lines changed

packages/internal-test-utils/ReactInternalTestUtils.js

Lines changed: 126 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,129 @@
55
* LICENSE file in the root directory of this source tree.
66
*/
77

8-
// TODO: Move `internalAct` and other test helpers to this package
8+
// TODO: Move `internalAct` and other test helpers to this package, too
9+
10+
import * as SchedulerMock from 'scheduler/unstable_mock';
11+
import {diff} from 'jest-diff';
12+
import {equals} from '@jest/expect-utils';
13+
14+
function assertYieldsWereCleared(Scheduler) {
15+
const actualYields = Scheduler.unstable_clearYields();
16+
if (actualYields.length !== 0) {
17+
const error = Error(
18+
'Log of yielded values is not empty. ' +
19+
'Call expect(ReactTestRenderer).unstable_toHaveYielded(...) first.',
20+
);
21+
Error.captureStackTrace(error, assertYieldsWereCleared);
22+
throw error;
23+
}
24+
}
25+
26+
export async function waitFor(expectedLog) {
27+
assertYieldsWereCleared(SchedulerMock);
28+
29+
// Create the error object before doing any async work, to get a better
30+
// stack trace.
31+
const error = new Error();
32+
Error.captureStackTrace(error, waitFor);
33+
34+
const actualLog = [];
35+
do {
36+
// Wait until end of current task/microtask.
37+
await null;
38+
if (SchedulerMock.unstable_hasPendingWork()) {
39+
SchedulerMock.unstable_flushNumberOfYields(
40+
expectedLog.length - actualLog.length,
41+
);
42+
actualLog.push(...SchedulerMock.unstable_clearYields());
43+
if (expectedLog.length > actualLog.length) {
44+
// Continue flushing until we've logged the expected number of items.
45+
} else {
46+
// Once we've reached the expected sequence, wait one more microtask to
47+
// flush any remaining synchronous work.
48+
await null;
49+
actualLog.push(...SchedulerMock.unstable_clearYields());
50+
break;
51+
}
52+
} else {
53+
// There's no pending work, even after a microtask.
54+
break;
55+
}
56+
} while (true);
57+
58+
if (equals(actualLog, expectedLog)) {
59+
return;
60+
}
61+
62+
error.message = `
63+
Expected sequence of events did not occur.
64+
65+
${diff(expectedLog, actualLog)}
66+
`;
67+
throw error;
68+
}
69+
70+
export async function waitForAll(expectedLog) {
71+
assertYieldsWereCleared(SchedulerMock);
72+
73+
// Create the error object before doing any async work, to get a better
74+
// stack trace.
75+
const error = new Error();
76+
Error.captureStackTrace(error, waitFor);
77+
78+
do {
79+
// Wait until end of current task/microtask.
80+
await null;
81+
if (!SchedulerMock.unstable_hasPendingWork()) {
82+
// There's no pending work, even after a microtask. Stop flushing.
83+
break;
84+
}
85+
SchedulerMock.unstable_flushAllWithoutAsserting();
86+
} while (true);
87+
88+
const actualLog = SchedulerMock.unstable_clearYields();
89+
if (equals(actualLog, expectedLog)) {
90+
return;
91+
}
92+
93+
error.message = `
94+
Expected sequence of events did not occur.
95+
96+
${diff(expectedLog, actualLog)}
97+
`;
98+
throw error;
99+
}
100+
101+
// TODO: This name is a bit misleading currently because it will stop as soon as
102+
// React yields for any reason, not just for a paint. I've left it this way for
103+
// now because that's how untable_flushUntilNextPaint already worked, but maybe
104+
// we should split these use cases into separate APIs.
105+
export async function waitForPaint(expectedLog) {
106+
assertYieldsWereCleared(SchedulerMock);
107+
108+
// Create the error object before doing any async work, to get a better
109+
// stack trace.
110+
const error = new Error();
111+
Error.captureStackTrace(error, waitFor);
112+
113+
// Wait until end of current task/microtask.
114+
await null;
115+
if (SchedulerMock.unstable_hasPendingWork()) {
116+
// Flush until React yields.
117+
SchedulerMock.unstable_flushUntilNextPaint();
118+
// Wait one more microtask to flush any remaining synchronous work.
119+
await null;
120+
}
121+
122+
const actualLog = SchedulerMock.unstable_clearYields();
123+
if (equals(actualLog, expectedLog)) {
124+
return;
125+
}
126+
127+
error.message = `
128+
Expected sequence of events did not occur.
129+
130+
${diff(expectedLog, actualLog)}
131+
`;
132+
throw error;
133+
}

packages/jest-react/src/JestReact.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,12 @@ function assertYieldsWereCleared(root) {
3131
const Scheduler = root._Scheduler;
3232
const actualYields = Scheduler.unstable_clearYields();
3333
if (actualYields.length !== 0) {
34-
throw new Error(
34+
const error = Error(
3535
'Log of yielded values is not empty. ' +
3636
'Call expect(ReactTestRenderer).unstable_toHaveYielded(...) first.',
3737
);
38+
Error.captureStackTrace(error, assertYieldsWereCleared);
39+
throw error;
3840
}
3941
}
4042

packages/react-reconciler/src/__tests__/ReactSuspenseWithNoopRenderer-test.js

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@ let Fragment;
33
let ReactNoop;
44
let Scheduler;
55
let act;
6+
let waitFor;
7+
let waitForAll;
8+
let waitForPaint;
69
let Suspense;
710
let getCacheForType;
811

@@ -19,6 +22,10 @@ describe('ReactSuspenseWithNoopRenderer', () => {
1922
Scheduler = require('scheduler');
2023
act = require('jest-react').act;
2124
Suspense = React.Suspense;
25+
const InternalTestUtils = require('internal-test-utils');
26+
waitFor = InternalTestUtils.waitFor;
27+
waitForAll = InternalTestUtils.waitForAll;
28+
waitForPaint = InternalTestUtils.waitForPaint;
2229

2330
getCacheForType = React.unstable_getCacheForType;
2431

@@ -208,7 +215,7 @@ describe('ReactSuspenseWithNoopRenderer', () => {
208215
React.startTransition(() => {
209216
ReactNoop.render(<Foo />);
210217
});
211-
expect(Scheduler).toFlushAndYieldThrough([
218+
await waitFor([
212219
'Foo',
213220
'Bar',
214221
// A suspends
@@ -226,7 +233,7 @@ describe('ReactSuspenseWithNoopRenderer', () => {
226233

227234
// Even though the promise has resolved, we should now flush
228235
// and commit the in progress render instead of restarting.
229-
expect(Scheduler).toFlushAndYield(['D']);
236+
await waitForPaint(['D']);
230237
expect(ReactNoop).toMatchRenderedOutput(
231238
<>
232239
<span prop="Loading..." />
@@ -235,11 +242,8 @@ describe('ReactSuspenseWithNoopRenderer', () => {
235242
</>,
236243
);
237244

238-
// Await one micro task to attach the retry listeners.
239-
await null;
240-
241245
// Next, we'll flush the complete content.
242-
expect(Scheduler).toFlushAndYield(['Bar', 'A', 'B']);
246+
await waitForAll(['Bar', 'A', 'B']);
243247

244248
expect(ReactNoop).toMatchRenderedOutput(
245249
<>

scripts/jest/matchers/schedulerTestMatchers.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,14 @@ function captureAssertion(fn) {
1818

1919
function assertYieldsWereCleared(Scheduler) {
2020
const actualYields = Scheduler.unstable_clearYields();
21+
2122
if (actualYields.length !== 0) {
22-
throw new Error(
23+
const error = Error(
2324
'Log of yielded values is not empty. ' +
2425
'Call expect(Scheduler).toHaveYielded(...) first.'
2526
);
27+
Error.captureStackTrace(error, assertYieldsWereCleared);
28+
throw error;
2629
}
2730
}
2831

0 commit comments

Comments
 (0)