forked from facebook/react
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathReactTransition-test.js
551 lines (503 loc) · 15.1 KB
/
ReactTransition-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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
* @jest-environment node
*/
'use strict';
let React;
let ReactNoop;
let Scheduler;
let Suspense;
let useState;
let useTransition;
let startTransition;
let act;
let getCacheForType;
let caches;
let seededCache;
describe('ReactTransition', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactNoop = require('react-noop-renderer');
Scheduler = require('scheduler');
useState = React.useState;
useTransition = React.unstable_useTransition;
Suspense = React.Suspense;
startTransition = React.unstable_startTransition;
getCacheForType = React.unstable_getCacheForType;
act = ReactNoop.act;
caches = [];
seededCache = null;
});
function createTextCache() {
if (seededCache !== null) {
// Trick to seed a cache before it exists.
// TODO: Need a built-in API to seed data before the initial render (i.e.
// not a refresh because nothing has mounted yet).
const cache = seededCache;
seededCache = null;
return cache;
}
const data = new Map();
const version = caches.length + 1;
const cache = {
version,
data,
resolve(text) {
const record = data.get(text);
if (record === undefined) {
const newRecord = {
status: 'resolved',
value: text,
};
data.set(text, newRecord);
} else if (record.status === 'pending') {
const thenable = record.value;
record.status = 'resolved';
record.value = text;
thenable.pings.forEach(t => t());
}
},
reject(text, error) {
const record = data.get(text);
if (record === undefined) {
const newRecord = {
status: 'rejected',
value: error,
};
data.set(text, newRecord);
} else if (record.status === 'pending') {
const thenable = record.value;
record.status = 'rejected';
record.value = error;
thenable.pings.forEach(t => t());
}
},
};
caches.push(cache);
return cache;
}
function readText(text) {
const textCache = getCacheForType(createTextCache);
const record = textCache.data.get(text);
if (record !== undefined) {
switch (record.status) {
case 'pending':
Scheduler.unstable_yieldValue(`Suspend! [${text}]`);
throw record.value;
case 'rejected':
Scheduler.unstable_yieldValue(`Error! [${text}]`);
throw record.value;
case 'resolved':
return textCache.version;
}
} else {
Scheduler.unstable_yieldValue(`Suspend! [${text}]`);
const thenable = {
pings: [],
then(resolve) {
if (newRecord.status === 'pending') {
thenable.pings.push(resolve);
} else {
Promise.resolve().then(() => resolve(newRecord.value));
}
},
};
const newRecord = {
status: 'pending',
value: thenable,
};
textCache.data.set(text, newRecord);
throw thenable;
}
}
function Text({text}) {
Scheduler.unstable_yieldValue(text);
return text;
}
function AsyncText({text}) {
readText(text);
Scheduler.unstable_yieldValue(text);
return text;
}
function seedNextTextCache(text) {
if (seededCache === null) {
seededCache = createTextCache();
}
seededCache.resolve(text);
}
function resolveText(text) {
if (caches.length === 0) {
throw Error('Cache does not exist.');
} else {
// Resolve the most recently created cache. An older cache can by
// resolved with `caches[index].resolve(text)`.
caches[caches.length - 1].resolve(text);
}
}
// @gate experimental
// @gate enableCache
test('isPending works even if called from outside an input event', async () => {
let start;
function App() {
const [show, setShow] = useState(false);
const [_start, isPending] = useTransition();
start = () => _start(() => setShow(true));
return (
<Suspense fallback={<Text text="Loading..." />}>
{isPending ? <Text text="Pending..." /> : null}
{show ? <AsyncText text="Async" /> : <Text text="(empty)" />}
</Suspense>
);
}
const root = ReactNoop.createRoot();
await act(async () => {
root.render(<App />);
});
expect(Scheduler).toHaveYielded(['(empty)']);
expect(root).toMatchRenderedOutput('(empty)');
await act(async () => {
start();
expect(Scheduler).toFlushAndYield([
'Pending...',
'(empty)',
'Suspend! [Async]',
'Loading...',
]);
expect(root).toMatchRenderedOutput('Pending...(empty)');
await resolveText('Async');
});
expect(Scheduler).toHaveYielded(['Async']);
expect(root).toMatchRenderedOutput('Async');
});
// @gate experimental
// @gate enableCache
test(
'when multiple transitions update the same queue, only the most recent ' +
'one is allowed to finish (no intermediate states)',
async () => {
let update;
function App() {
const [startContentChange, isContentPending] = useTransition();
const [label, setLabel] = useState('A');
const [contents, setContents] = useState('A');
update = value => {
ReactNoop.discreteUpdates(() => {
setLabel(value);
startContentChange(() => {
setContents(value);
});
});
};
return (
<>
<Text
text={
label + ' label' + (isContentPending ? ' (loading...)' : '')
}
/>
<div>
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text={contents + ' content'} />
</Suspense>
</div>
</>
);
}
// Initial render
const root = ReactNoop.createRoot();
await act(async () => {
seedNextTextCache('A content');
root.render(<App />);
});
expect(Scheduler).toHaveYielded(['A label', 'A content']);
expect(root).toMatchRenderedOutput(
<>
A label<div>A content</div>
</>,
);
// Switch to B
await act(async () => {
update('B');
});
expect(Scheduler).toHaveYielded([
// Commit pending state
'B label (loading...)',
'A content',
// Attempt to render B, but it suspends
'B label',
'Suspend! [B content]',
'Loading...',
]);
// This is a refresh transition so it shouldn't show a fallback
expect(root).toMatchRenderedOutput(
<>
B label (loading...)<div>A content</div>
</>,
);
// Before B finishes loading, switch to C
await act(async () => {
update('C');
});
expect(Scheduler).toHaveYielded([
// Commit pending state
'C label (loading...)',
'A content',
// Attempt to render C, but it suspends
'C label',
'Suspend! [C content]',
'Loading...',
]);
expect(root).toMatchRenderedOutput(
<>
C label (loading...)<div>A content</div>
</>,
);
// Finish loading B. But we're not allowed to render B because it's
// entangled with C. So we're still pending.
await act(async () => {
resolveText('B content');
});
expect(Scheduler).toHaveYielded([
// Attempt to render C, but it suspends
'C label',
'Suspend! [C content]',
'Loading...',
]);
expect(root).toMatchRenderedOutput(
<>
C label (loading...)<div>A content</div>
</>,
);
// Now finish loading C. This is the terminal update, so it can finish.
await act(async () => {
resolveText('C content');
});
expect(Scheduler).toHaveYielded(['C label', 'C content']);
expect(root).toMatchRenderedOutput(
<>
C label<div>C content</div>
</>,
);
},
);
// Same as previous test, but for class update queue.
// @gate experimental
// @gate enableCache
test(
'when multiple transitions update the same queue, only the most recent ' +
'one is allowed to finish (no intermediate states) (classes)',
async () => {
let update;
class App extends React.Component {
state = {
label: 'A',
contents: 'A',
};
render() {
update = value => {
ReactNoop.discreteUpdates(() => {
this.setState({label: value});
startTransition(() => {
this.setState({contents: value});
});
});
};
const label = this.state.label;
const contents = this.state.contents;
const isContentPending = label !== contents;
return (
<>
<Text
text={
label + ' label' + (isContentPending ? ' (loading...)' : '')
}
/>
<div>
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text={contents + ' content'} />
</Suspense>
</div>
</>
);
}
}
// Initial render
const root = ReactNoop.createRoot();
await act(async () => {
seedNextTextCache('A content');
root.render(<App />);
});
expect(Scheduler).toHaveYielded(['A label', 'A content']);
expect(root).toMatchRenderedOutput(
<>
A label<div>A content</div>
</>,
);
// Switch to B
await act(async () => {
update('B');
});
expect(Scheduler).toHaveYielded([
// Commit pending state
'B label (loading...)',
'A content',
// Attempt to render B, but it suspends
'B label',
'Suspend! [B content]',
'Loading...',
]);
// This is a refresh transition so it shouldn't show a fallback
expect(root).toMatchRenderedOutput(
<>
B label (loading...)<div>A content</div>
</>,
);
// Before B finishes loading, switch to C
await act(async () => {
update('C');
});
expect(Scheduler).toHaveYielded([
// Commit pending state
'C label (loading...)',
'A content',
// Attempt to render C, but it suspends
'C label',
'Suspend! [C content]',
'Loading...',
]);
expect(root).toMatchRenderedOutput(
<>
C label (loading...)<div>A content</div>
</>,
);
// Finish loading B. But we're not allowed to render B because it's
// entangled with C. So we're still pending.
await act(async () => {
resolveText('B content');
});
expect(Scheduler).toHaveYielded([
// Attempt to render C, but it suspends
'C label',
'Suspend! [C content]',
'Loading...',
]);
expect(root).toMatchRenderedOutput(
<>
C label (loading...)<div>A content</div>
</>,
);
// Now finish loading C. This is the terminal update, so it can finish.
await act(async () => {
resolveText('C content');
});
expect(Scheduler).toHaveYielded(['C label', 'C content']);
expect(root).toMatchRenderedOutput(
<>
C label<div>C content</div>
</>,
);
},
);
// @gate experimental
// @gate enableCache
test(
'when multiple transitions update overlapping queues, all the transitions ' +
'across all the queues are entangled',
async () => {
let setShowA;
let setShowB;
let setShowC;
function App() {
const [showA, _setShowA] = useState(false);
const [showB, _setShowB] = useState(false);
const [showC, _setShowC] = useState(false);
setShowA = _setShowA;
setShowB = _setShowB;
setShowC = _setShowC;
// Only one of these children should be visible at a time. Except
// instead of being modeled as a single state, it's three separate
// states that are updated simultaneously. This may seem a bit
// contrived, but it's more common than you might think. Usually via
// a framework or indirection. For example, consider a tooltip manager
// that only shows a single tooltip at a time. Or a router that
// highlights links to the active route.
return (
<>
<Suspense fallback={<Text text="Loading..." />}>
{showA ? <AsyncText text="A" /> : null}
{showB ? <AsyncText text="B" /> : null}
{showC ? <AsyncText text="C" /> : null}
</Suspense>
</>
);
}
// Initial render. Start with all children hidden.
const root = ReactNoop.createRoot();
await act(async () => {
root.render(<App />);
});
expect(Scheduler).toHaveYielded([]);
expect(root).toMatchRenderedOutput(null);
// Switch to A.
await act(async () => {
startTransition(() => {
setShowA(true);
});
});
expect(Scheduler).toHaveYielded(['Suspend! [A]', 'Loading...']);
expect(root).toMatchRenderedOutput(null);
// Before A loads, switch to B. This should entangle A with B.
await act(async () => {
startTransition(() => {
setShowA(false);
setShowB(true);
});
});
expect(Scheduler).toHaveYielded(['Suspend! [B]', 'Loading...']);
expect(root).toMatchRenderedOutput(null);
// Before A or B loads, switch to C. This should entangle C with B, and
// transitively entangle C with A.
await act(async () => {
startTransition(() => {
setShowB(false);
setShowC(true);
});
});
expect(Scheduler).toHaveYielded(['Suspend! [C]', 'Loading...']);
expect(root).toMatchRenderedOutput(null);
// Now the data starts resolving out of order.
// First resolve B. This will attempt to render C, since everything is
// entangled.
await act(async () => {
startTransition(() => {
resolveText('B');
});
});
expect(Scheduler).toHaveYielded(['Suspend! [C]', 'Loading...']);
expect(root).toMatchRenderedOutput(null);
// Now resolve A. Again, this will attempt to render C, since everything
// is entangled.
await act(async () => {
startTransition(() => {
resolveText('A');
});
});
expect(Scheduler).toHaveYielded(['Suspend! [C]', 'Loading...']);
expect(root).toMatchRenderedOutput(null);
// Finally, resolve C. This time we can finish.
await act(async () => {
startTransition(() => {
resolveText('C');
});
});
expect(Scheduler).toHaveYielded(['C']);
expect(root).toMatchRenderedOutput('C');
},
);
});