-
Notifications
You must be signed in to change notification settings - Fork 47.7k
/
Copy pathReactIsomorphicAct-test.js
350 lines (296 loc) · 9.66 KB
/
ReactIsomorphicAct-test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @jest-environment node
*/
// sanity tests for act()
let React;
let ReactNoop;
let act;
let use;
let Suspense;
let DiscreteEventPriority;
let startTransition;
let waitForMicrotasks;
let Scheduler;
let assertLog;
describe('isomorphic act()', () => {
beforeEach(() => {
React = require('react');
Scheduler = require('scheduler');
ReactNoop = require('react-noop-renderer');
DiscreteEventPriority =
require('react-reconciler/constants').DiscreteEventPriority;
act = React.act;
use = React.use;
Suspense = React.Suspense;
startTransition = React.startTransition;
waitForMicrotasks = require('internal-test-utils').waitForMicrotasks;
assertLog = require('internal-test-utils').assertLog;
});
beforeEach(() => {
global.IS_REACT_ACT_ENVIRONMENT = true;
});
afterEach(() => {
jest.restoreAllMocks();
});
function Text({text}) {
Scheduler.log(text);
return text;
}
// @gate __DEV__
test('bypasses queueMicrotask', async () => {
const root = ReactNoop.createRoot();
// First test what happens without wrapping in act. This update would
// normally be queued in a microtask.
global.IS_REACT_ACT_ENVIRONMENT = false;
ReactNoop.unstable_runWithPriority(DiscreteEventPriority, () => {
root.render('A');
});
// Nothing has rendered yet
expect(root).toMatchRenderedOutput(null);
// Flush the microtasks by awaiting
await waitForMicrotasks();
expect(root).toMatchRenderedOutput('A');
// Now do the same thing but wrap the update with `act`. No
// `await` necessary.
global.IS_REACT_ACT_ENVIRONMENT = true;
act(() => {
ReactNoop.unstable_runWithPriority(DiscreteEventPriority, () => {
root.render('B');
});
});
expect(root).toMatchRenderedOutput('B');
});
// @gate __DEV__
test('return value – sync callback', async () => {
expect(await act(() => 'hi')).toEqual('hi');
});
// @gate __DEV__
test('return value – sync callback, nested', async () => {
const returnValue = await act(() => {
return act(() => 'hi');
});
expect(returnValue).toEqual('hi');
});
// @gate __DEV__
test('return value – async callback', async () => {
const returnValue = await act(async () => {
return await Promise.resolve('hi');
});
expect(returnValue).toEqual('hi');
});
// @gate __DEV__
test('return value – async callback, nested', async () => {
const returnValue = await act(async () => {
return await act(async () => {
return await Promise.resolve('hi');
});
});
expect(returnValue).toEqual('hi');
});
// @gate __DEV__
test('in legacy mode, updates are batched', () => {
const root = ReactNoop.createLegacyRoot();
// Outside of `act`, legacy updates are flushed completely synchronously
root.render('A');
expect(root).toMatchRenderedOutput('A');
// `act` will batch the updates and flush them at the end
act(() => {
root.render('B');
// Hasn't flushed yet
expect(root).toMatchRenderedOutput('A');
// Confirm that a nested `batchedUpdates` call won't cause the updates
// to flush early.
ReactNoop.batchedUpdates(() => {
root.render('C');
});
// Still hasn't flushed
expect(root).toMatchRenderedOutput('A');
});
// Now everything renders in a single batch.
expect(root).toMatchRenderedOutput('C');
});
// @gate __DEV__
test('in legacy mode, in an async scope, updates are batched until the first `await`', async () => {
const root = ReactNoop.createLegacyRoot();
await act(async () => {
queueMicrotask(() => {
Scheduler.log('Current tree in microtask: ' + root.getChildrenAsJSX());
root.render(<Text text="C" />);
});
root.render(<Text text="A" />);
root.render(<Text text="B" />);
await null;
assertLog([
// A and B should render in a single batch _before_ the microtask queue
// has run. This replicates the behavior of the original `act`
// implementation, for compatibility.
'B',
'Current tree in microtask: B',
// C isn't scheduled until a microtask, so it's rendered separately.
'C',
]);
// Subsequent updates should also render in separate batches.
root.render(<Text text="D" />);
root.render(<Text text="E" />);
assertLog(['D', 'E']);
});
});
// @gate __DEV__
test('in legacy mode, in an async scope, updates are batched until the first `await` (regression test: batchedUpdates)', async () => {
const root = ReactNoop.createLegacyRoot();
await act(async () => {
queueMicrotask(() => {
Scheduler.log('Current tree in microtask: ' + root.getChildrenAsJSX());
root.render(<Text text="C" />);
});
// This is a regression test. The presence of `batchedUpdates` would cause
// these updates to not flush until a microtask. The correct behavior is
// that they flush before the microtask queue, regardless of whether
// they are wrapped with `batchedUpdates`.
ReactNoop.batchedUpdates(() => {
root.render(<Text text="A" />);
root.render(<Text text="B" />);
});
await null;
assertLog([
// A and B should render in a single batch _before_ the microtask queue
// has run. This replicates the behavior of the original `act`
// implementation, for compatibility.
'B',
'Current tree in microtask: B',
// C isn't scheduled until a microtask, so it's rendered separately.
'C',
]);
// Subsequent updates should also render in separate batches.
root.render(<Text text="D" />);
root.render(<Text text="E" />);
assertLog(['D', 'E']);
});
});
// @gate __DEV__
test('unwraps promises by yielding to microtasks (async act scope)', async () => {
const promise = Promise.resolve('Async');
function Fallback() {
throw new Error('Fallback should never be rendered');
}
function App() {
return use(promise);
}
const root = ReactNoop.createRoot();
await act(async () => {
startTransition(() => {
root.render(
<Suspense fallback={<Fallback />}>
<App />
</Suspense>,
);
});
});
expect(root).toMatchRenderedOutput('Async');
});
// @gate __DEV__
test('unwraps promises by yielding to microtasks (non-async act scope)', async () => {
const promise = Promise.resolve('Async');
function Fallback() {
throw new Error('Fallback should never be rendered');
}
function App() {
return use(promise);
}
const root = ReactNoop.createRoot();
// Note that the scope function is not an async function
await act(() => {
startTransition(() => {
root.render(
<Suspense fallback={<Fallback />}>
<App />
</Suspense>,
);
});
});
expect(root).toMatchRenderedOutput('Async');
});
// @gate __DEV__
test('warns if a promise is used in a non-awaited `act` scope', async () => {
const promise = new Promise(() => {});
function Fallback() {
throw new Error('Fallback should never be rendered');
}
function App() {
return use(promise);
}
spyOnDev(console, 'error').mockImplementation(() => {});
const root = ReactNoop.createRoot();
act(() => {
startTransition(() => {
root.render(
<Suspense fallback={<Fallback />}>
<App />
</Suspense>,
);
});
});
// `act` warns after a few microtasks, instead of a macrotask, so that it's
// more likely to be attributed to the correct test case.
//
// The exact number of microtasks is an implementation detail; just needs
// to happen when the microtask queue is flushed.
await waitForMicrotasks();
expect(console.error).toHaveBeenCalledTimes(1);
expect(console.error.mock.calls[0][0]).toContain(
'Warning: A component suspended inside an `act` scope, but the `act` ' +
'call was not awaited. When testing React components that ' +
'depend on asynchronous data, you must await the result:\n\n' +
'await act(() => ...)',
);
});
// @gate __DEV__
test('does not warn when suspending via legacy `throw` API in non-awaited `act` scope', async () => {
let didResolve = false;
let resolvePromise;
const promise = new Promise(r => {
resolvePromise = () => {
didResolve = true;
r();
};
});
function Fallback() {
return 'Loading...';
}
function App() {
if (!didResolve) {
throw promise;
}
return 'Async';
}
spyOnDev(console, 'error').mockImplementation(() => {});
const root = ReactNoop.createRoot();
act(() => {
startTransition(() => {
root.render(
<Suspense fallback={<Fallback />}>
<App />
</Suspense>,
);
});
});
expect(root).toMatchRenderedOutput('Loading...');
// `act` warns after a few microtasks, instead of a macrotask, so that it's
// more likely to be attributed to the correct test case.
//
// The exact number of microtasks is an implementation detail; just needs
// to happen when the microtask queue is flushed.
await waitForMicrotasks();
expect(console.error).toHaveBeenCalledTimes(0);
// Finish loading the data
await act(async () => {
resolvePromise();
});
expect(root).toMatchRenderedOutput('Async');
});
});