forked from facebook/react
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathReactSuspenseWithNoopRenderer-test.js
4046 lines (3565 loc) · 121 KB
/
ReactSuspenseWithNoopRenderer-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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
let React;
let Fragment;
let ReactNoop;
let Scheduler;
let Suspense;
let textCache;
let readText;
let resolveText;
let rejectText;
describe('ReactSuspenseWithNoopRenderer', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
Fragment = React.Fragment;
ReactNoop = require('react-noop-renderer');
Scheduler = require('scheduler');
Suspense = React.Suspense;
textCache = new Map();
readText = text => {
const record = textCache.get(text);
if (record !== undefined) {
switch (record.status) {
case 'pending':
throw record.promise;
case 'rejected':
throw Error('Failed to load: ' + text);
case 'resolved':
return text;
}
} else {
let ping;
const promise = new Promise(resolve => (ping = resolve));
const newRecord = {
status: 'pending',
ping: ping,
promise,
};
textCache.set(text, newRecord);
throw promise;
}
};
resolveText = text => {
const record = textCache.get(text);
if (record !== undefined) {
if (record.status === 'pending') {
Scheduler.unstable_yieldValue(`Promise resolved [${text}]`);
record.ping();
record.ping = null;
record.status = 'resolved';
clearTimeout(record.promise._timer);
record.promise = null;
}
} else {
const newRecord = {
ping: null,
status: 'resolved',
promise: null,
};
textCache.set(text, newRecord);
}
};
rejectText = text => {
const record = textCache.get(text);
if (record !== undefined) {
if (record.status === 'pending') {
Scheduler.unstable_yieldValue(`Promise rejected [${text}]`);
record.ping();
record.status = 'rejected';
clearTimeout(record.promise._timer);
record.promise = null;
}
} else {
const newRecord = {
ping: null,
status: 'rejected',
promise: null,
};
textCache.set(text, newRecord);
}
};
});
// function div(...children) {
// children = children.map(
// c => (typeof c === 'string' ? {text: c, hidden: false} : c),
// );
// return {type: 'div', children, prop: undefined, hidden: false};
// }
function span(prop) {
return {type: 'span', children: [], prop, hidden: false};
}
function hiddenSpan(prop) {
return {type: 'span', children: [], prop, hidden: true};
}
function advanceTimers(ms) {
// Note: This advances Jest's virtual time but not React's. Use
// ReactNoop.expire for that.
if (typeof ms !== 'number') {
throw new Error('Must specify ms');
}
jest.advanceTimersByTime(ms);
// Wait until the end of the current tick
// We cannot use a timer since we're faking them
return Promise.resolve().then(() => {});
}
function Text(props) {
Scheduler.unstable_yieldValue(props.text);
return <span prop={props.text} ref={props.hostRef} />;
}
function AsyncText(props) {
const text = props.text;
try {
readText(text);
Scheduler.unstable_yieldValue(text);
return <span prop={text} />;
} catch (promise) {
if (typeof promise.then === 'function') {
Scheduler.unstable_yieldValue(`Suspend! [${text}]`);
if (typeof props.ms === 'number' && promise._timer === undefined) {
promise._timer = setTimeout(() => {
resolveText(text);
}, props.ms);
}
} else {
Scheduler.unstable_yieldValue(`Error! [${text}]`);
}
throw promise;
}
}
// Note: This is based on a similar component we use in www. We can delete
// once the extra div wrapper is no longer necessary.
function LegacyHiddenDiv({children, mode}) {
return (
<div hidden={mode === 'hidden'}>
<React.unstable_LegacyHidden
mode={mode === 'hidden' ? 'unstable-defer-without-hiding' : mode}>
{children}
</React.unstable_LegacyHidden>
</div>
);
}
it('does not restart rendering for initial render', async () => {
function Bar(props) {
Scheduler.unstable_yieldValue('Bar');
return props.children;
}
function Foo() {
Scheduler.unstable_yieldValue('Foo');
return (
<>
<Suspense fallback={<Text text="Loading..." />}>
<Bar>
<AsyncText text="A" ms={100} />
<Text text="B" />
</Bar>
</Suspense>
<Text text="C" />
<Text text="D" />
</>
);
}
ReactNoop.render(<Foo />);
expect(Scheduler).toFlushAndYieldThrough([
'Foo',
'Bar',
// A suspends
'Suspend! [A]',
// But we keep rendering the siblings
'B',
'Loading...',
'C',
// We leave D incomplete.
]);
expect(ReactNoop.getChildren()).toEqual([]);
// Flush the promise completely
Scheduler.unstable_advanceTime(100);
await advanceTimers(100);
expect(Scheduler).toHaveYielded(['Promise resolved [A]']);
// Even though the promise has resolved, we should now flush
// and commit the in progress render instead of restarting.
expect(Scheduler).toFlushAndYield(['D']);
expect(ReactNoop.getChildren()).toEqual([
span('Loading...'),
span('C'),
span('D'),
]);
// Await one micro task to attach the retry listeners.
await null;
// Next, we'll flush the complete content.
expect(Scheduler).toFlushAndYield(['Bar', 'A', 'B']);
expect(ReactNoop.getChildren()).toEqual([
span('A'),
span('B'),
span('C'),
span('D'),
]);
});
it('suspends rendering and continues later', async () => {
function Bar(props) {
Scheduler.unstable_yieldValue('Bar');
return props.children;
}
function Foo({renderBar}) {
Scheduler.unstable_yieldValue('Foo');
return (
<Suspense fallback={<Text text="Loading..." />}>
{renderBar ? (
<Bar>
<AsyncText text="A" ms={100} />
<Text text="B" />
</Bar>
) : null}
</Suspense>
);
}
// Render empty shell.
ReactNoop.render(<Foo />);
expect(Scheduler).toFlushAndYield(['Foo']);
// The update will suspend.
ReactNoop.render(<Foo renderBar={true} />);
expect(Scheduler).toFlushAndYield([
'Foo',
'Bar',
// A suspends
'Suspend! [A]',
// But we keep rendering the siblings
'B',
'Loading...',
]);
expect(ReactNoop.getChildren()).toEqual([]);
// Flush some of the time
await advanceTimers(50);
// Still nothing...
expect(Scheduler).toFlushWithoutYielding();
expect(ReactNoop.getChildren()).toEqual([]);
// Flush the promise completely
await advanceTimers(50);
// Renders successfully
expect(Scheduler).toHaveYielded(['Promise resolved [A]']);
expect(Scheduler).toFlushAndYield(['Foo', 'Bar', 'A', 'B']);
expect(ReactNoop.getChildren()).toEqual([span('A'), span('B')]);
});
it('suspends siblings and later recovers each independently', async () => {
// Render two sibling Suspense components
ReactNoop.render(
<Fragment>
<Suspense fallback={<Text text="Loading A..." />}>
<AsyncText text="A" ms={5000} />
</Suspense>
<Suspense fallback={<Text text="Loading B..." />}>
<AsyncText text="B" ms={6000} />
</Suspense>
</Fragment>,
);
expect(Scheduler).toFlushAndYield([
'Suspend! [A]',
'Loading A...',
'Suspend! [B]',
'Loading B...',
]);
expect(ReactNoop.getChildren()).toEqual([
span('Loading A...'),
span('Loading B...'),
]);
// Advance time by enough that the first Suspense's promise resolves and
// switches back to the normal view. The second Suspense should still
// show the placeholder
ReactNoop.expire(5000);
await advanceTimers(5000);
expect(Scheduler).toHaveYielded(['Promise resolved [A]']);
expect(Scheduler).toFlushAndYield(['A']);
expect(ReactNoop.getChildren()).toEqual([span('A'), span('Loading B...')]);
// Advance time by enough that the second Suspense's promise resolves
// and switches back to the normal view
ReactNoop.expire(1000);
await advanceTimers(1000);
expect(Scheduler).toHaveYielded(['Promise resolved [B]']);
expect(Scheduler).toFlushAndYield(['B']);
expect(ReactNoop.getChildren()).toEqual([span('A'), span('B')]);
});
it('continues rendering siblings after suspending', async () => {
// A shell is needed. The update cause it to suspend.
ReactNoop.render(<Suspense fallback={<Text text="Loading..." />} />);
expect(Scheduler).toFlushAndYield([]);
// B suspends. Continue rendering the remaining siblings.
ReactNoop.render(
<Suspense fallback={<Text text="Loading..." />}>
<Text text="A" />
<AsyncText text="B" />
<Text text="C" />
<Text text="D" />
</Suspense>,
);
// B suspends. Continue rendering the remaining siblings.
expect(Scheduler).toFlushAndYield([
'A',
'Suspend! [B]',
'C',
'D',
'Loading...',
]);
// Did not commit yet.
expect(ReactNoop.getChildren()).toEqual([]);
// Wait for data to resolve
await resolveText('B');
// Renders successfully
expect(Scheduler).toHaveYielded(['Promise resolved [B]']);
expect(Scheduler).toFlushAndYield(['A', 'B', 'C', 'D']);
expect(ReactNoop.getChildren()).toEqual([
span('A'),
span('B'),
span('C'),
span('D'),
]);
});
// Second condition is redundant but guarantees that the test runs in prod.
// TODO: Delete this feature flag.
// @gate !replayFailedUnitOfWorkWithInvokeGuardedCallback || !__DEV__
it('retries on error', async () => {
class ErrorBoundary extends React.Component {
state = {error: null};
componentDidCatch(error) {
this.setState({error});
}
reset() {
this.setState({error: null});
}
render() {
if (this.state.error !== null) {
return <Text text={'Caught error: ' + this.state.error.message} />;
}
return this.props.children;
}
}
const errorBoundary = React.createRef();
function App({renderContent}) {
return (
<Suspense fallback={<Text text="Loading..." />}>
{renderContent ? (
<ErrorBoundary ref={errorBoundary}>
<AsyncText text="Result" ms={1000} />
</ErrorBoundary>
) : null}
</Suspense>
);
}
ReactNoop.render(<App />);
expect(Scheduler).toFlushAndYield([]);
expect(ReactNoop.getChildren()).toEqual([]);
ReactNoop.render(<App renderContent={true} />);
expect(Scheduler).toFlushAndYield(['Suspend! [Result]', 'Loading...']);
expect(ReactNoop.getChildren()).toEqual([]);
await rejectText('Result');
expect(Scheduler).toHaveYielded(['Promise rejected [Result]']);
expect(Scheduler).toFlushAndYield([
'Error! [Result]',
// React retries one more time
'Error! [Result]',
// Errored again on retry. Now handle it.
'Caught error: Failed to load: Result',
]);
expect(ReactNoop.getChildren()).toEqual([
span('Caught error: Failed to load: Result'),
]);
});
// Second condition is redundant but guarantees that the test runs in prod.
// TODO: Delete this feature flag.
// @gate !replayFailedUnitOfWorkWithInvokeGuardedCallback || !__DEV__
it('retries on error after falling back to a placeholder', async () => {
class ErrorBoundary extends React.Component {
state = {error: null};
componentDidCatch(error) {
this.setState({error});
}
reset() {
this.setState({error: null});
}
render() {
if (this.state.error !== null) {
return <Text text={'Caught error: ' + this.state.error.message} />;
}
return this.props.children;
}
}
const errorBoundary = React.createRef();
function App() {
return (
<Suspense fallback={<Text text="Loading..." />}>
<ErrorBoundary ref={errorBoundary}>
<AsyncText text="Result" ms={3000} />
</ErrorBoundary>
</Suspense>
);
}
ReactNoop.render(<App />);
expect(Scheduler).toFlushAndYield(['Suspend! [Result]', 'Loading...']);
expect(ReactNoop.getChildren()).toEqual([span('Loading...')]);
await rejectText('Result');
expect(Scheduler).toHaveYielded(['Promise rejected [Result]']);
expect(Scheduler).toFlushAndYield([
'Error! [Result]',
// React retries one more time
'Error! [Result]',
// Errored again on retry. Now handle it.
'Caught error: Failed to load: Result',
]);
expect(ReactNoop.getChildren()).toEqual([
span('Caught error: Failed to load: Result'),
]);
});
it('can update at a higher priority while in a suspended state', async () => {
function App(props) {
return (
<Suspense fallback={<Text text="Loading..." />}>
<Text text={props.highPri} />
<AsyncText text={props.lowPri} />
</Suspense>
);
}
// Initial mount
ReactNoop.render(<App highPri="A" lowPri="1" />);
expect(Scheduler).toFlushAndYield(['A', 'Suspend! [1]', 'Loading...']);
await resolveText('1');
expect(Scheduler).toHaveYielded(['Promise resolved [1]']);
expect(Scheduler).toFlushAndYield(['A', '1']);
expect(ReactNoop.getChildren()).toEqual([span('A'), span('1')]);
// Update the low-pri text
ReactNoop.render(<App highPri="A" lowPri="2" />);
expect(Scheduler).toFlushAndYield([
'A',
// Suspends
'Suspend! [2]',
'Loading...',
]);
// While we're still waiting for the low-pri update to complete, update the
// high-pri text at high priority.
ReactNoop.flushSync(() => {
ReactNoop.render(<App highPri="B" lowPri="1" />);
});
expect(Scheduler).toHaveYielded(['B', '1']);
expect(ReactNoop.getChildren()).toEqual([span('B'), span('1')]);
// Unblock the low-pri text and finish
await resolveText('2');
expect(Scheduler).toHaveYielded(['Promise resolved [2]']);
expect(ReactNoop.getChildren()).toEqual([span('B'), span('1')]);
});
it('keeps working on lower priority work after being pinged', async () => {
// Advance the virtual time so that we're close to the edge of a bucket.
ReactNoop.expire(149);
function App(props) {
return (
<Suspense fallback={<Text text="Loading..." />}>
{props.showA && <AsyncText text="A" />}
{props.showB && <Text text="B" />}
</Suspense>
);
}
ReactNoop.render(<App showA={false} showB={false} />);
expect(Scheduler).toFlushAndYield([]);
expect(ReactNoop.getChildren()).toEqual([]);
ReactNoop.render(<App showA={true} showB={false} />);
expect(Scheduler).toFlushAndYield(['Suspend! [A]', 'Loading...']);
expect(ReactNoop.getChildren()).toEqual([]);
// Advance React's virtual time by enough to fall into a new async bucket,
// but not enough to expire the suspense timeout.
ReactNoop.expire(120);
ReactNoop.render(<App showA={true} showB={true} />);
expect(Scheduler).toFlushAndYield(['Suspend! [A]', 'B', 'Loading...']);
expect(ReactNoop.getChildren()).toEqual([]);
await resolveText('A');
expect(Scheduler).toHaveYielded(['Promise resolved [A]']);
expect(Scheduler).toFlushAndYield(['A', 'B']);
expect(ReactNoop.getChildren()).toEqual([span('A'), span('B')]);
});
it('tries rendering a lower priority pending update even if a higher priority one suspends', async () => {
function App(props) {
if (props.hide) {
return <Text text="(empty)" />;
}
return (
<Suspense fallback="Loading...">
<AsyncText ms={2000} text="Async" />
</Suspense>
);
}
// Schedule a high pri update and a low pri update, without rendering in
// between.
ReactNoop.discreteUpdates(() => {
// High pri
ReactNoop.render(<App />);
});
// Low pri
ReactNoop.render(<App hide={true} />);
expect(Scheduler).toFlushAndYield([
// The first update suspends
'Suspend! [Async]',
// but we have another pending update that we can work on
'(empty)',
]);
expect(ReactNoop.getChildren()).toEqual([span('(empty)')]);
});
// Note: This test was written to test a heuristic used in the expiration
// times model. Might not make sense in the new model.
it('tries each subsequent level after suspending', async () => {
const root = ReactNoop.createRoot();
function App({step, shouldSuspend}) {
return (
<Suspense fallback="Loading...">
<Text text="Sibling" />
{shouldSuspend ? (
<AsyncText text={'Step ' + step} />
) : (
<Text text={'Step ' + step} />
)}
</Suspense>
);
}
function interrupt() {
// React has a heuristic to batch all updates that occur within the same
// event. This is a trick to circumvent that heuristic.
ReactNoop.flushSync(() => {
ReactNoop.renderToRootWithID(null, 'other-root');
});
}
// Mount the Suspense boundary without suspending, so that the subsequent
// updates suspend with a delay.
await ReactNoop.act(async () => {
root.render(<App step={0} shouldSuspend={false} />);
});
await advanceTimers(1000);
expect(Scheduler).toHaveYielded(['Sibling', 'Step 0']);
// Schedule an update at several distinct expiration times
await ReactNoop.act(async () => {
root.render(<App step={1} shouldSuspend={true} />);
Scheduler.unstable_advanceTime(1000);
expect(Scheduler).toFlushAndYieldThrough(['Sibling']);
interrupt();
root.render(<App step={2} shouldSuspend={true} />);
Scheduler.unstable_advanceTime(1000);
expect(Scheduler).toFlushAndYieldThrough(['Sibling']);
interrupt();
root.render(<App step={3} shouldSuspend={true} />);
Scheduler.unstable_advanceTime(1000);
expect(Scheduler).toFlushAndYieldThrough(['Sibling']);
interrupt();
root.render(<App step={4} shouldSuspend={false} />);
});
expect(Scheduler).toHaveYielded([
// The new reconciler batches everything together, so it finishes without
// suspending again.
'Sibling',
// NOTE: The final of the update got pushed into a lower priority range of
// lanes, leading to the extra intermediate render. This is because when
// we schedule the fourth update, we're already in the middle of rendering
// the three others. Since there are only three lanes in the default
// range, the fourth lane is shifted to slightly lower priority. This
// could easily change when we tweak our batching heuristics. Ideally,
// they'd all have default priority and render in a single batch.
'Suspend! [Step 3]',
'Sibling',
'Step 4',
]);
});
it('forces an expiration after an update times out', async () => {
ReactNoop.render(
<Fragment>
<Suspense fallback={<Text text="Loading..." />} />
</Fragment>,
);
expect(Scheduler).toFlushAndYield([]);
ReactNoop.render(
<Fragment>
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text="Async" ms={20000} />
</Suspense>
<Text text="Sync" />
</Fragment>,
);
expect(Scheduler).toFlushAndYield([
// The async child suspends
'Suspend! [Async]',
// Render the placeholder
'Loading...',
// Continue on the sibling
'Sync',
]);
// The update hasn't expired yet, so we commit nothing.
expect(ReactNoop.getChildren()).toEqual([]);
// Advance both React's virtual time and Jest's timers by enough to expire
// the update, but not by enough to flush the suspending promise.
ReactNoop.expire(10000);
await advanceTimers(10000);
// No additional rendering work is required, since we already prepared
// the placeholder.
expect(Scheduler).toHaveYielded([]);
// Should have committed the placeholder.
expect(ReactNoop.getChildren()).toEqual([span('Loading...'), span('Sync')]);
// Once the promise resolves, we render the suspended view
await advanceTimers(10000);
expect(Scheduler).toHaveYielded(['Promise resolved [Async]']);
expect(Scheduler).toFlushAndYield(['Async']);
expect(ReactNoop.getChildren()).toEqual([span('Async'), span('Sync')]);
});
it('switches to an inner fallback after suspending for a while', async () => {
// Advance the virtual time so that we're closer to the edge of a bucket.
ReactNoop.expire(200);
ReactNoop.render(
<Fragment>
<Text text="Sync" />
<Suspense fallback={<Text text="Loading outer..." />}>
<AsyncText text="Outer content" ms={300} />
<Suspense fallback={<Text text="Loading inner..." />}>
<AsyncText text="Inner content" ms={1000} />
</Suspense>
</Suspense>
</Fragment>,
);
expect(Scheduler).toFlushAndYield([
'Sync',
// The async content suspends
'Suspend! [Outer content]',
'Suspend! [Inner content]',
'Loading inner...',
'Loading outer...',
]);
// The outer loading state finishes immediately.
expect(ReactNoop.getChildren()).toEqual([
span('Sync'),
span('Loading outer...'),
]);
// Resolve the outer promise.
ReactNoop.expire(300);
await advanceTimers(300);
expect(Scheduler).toHaveYielded(['Promise resolved [Outer content]']);
expect(Scheduler).toFlushAndYield([
'Outer content',
'Suspend! [Inner content]',
'Loading inner...',
]);
// Don't commit the inner placeholder yet.
expect(ReactNoop.getChildren()).toEqual([
span('Sync'),
span('Loading outer...'),
]);
// Expire the inner timeout.
ReactNoop.expire(500);
await advanceTimers(500);
// Now that 750ms have elapsed since the outer placeholder timed out,
// we can timeout the inner placeholder.
expect(ReactNoop.getChildren()).toEqual([
span('Sync'),
span('Outer content'),
span('Loading inner...'),
]);
// Finally, flush the inner promise. We should see the complete screen.
ReactNoop.expire(1000);
await advanceTimers(1000);
expect(Scheduler).toHaveYielded(['Promise resolved [Inner content]']);
expect(Scheduler).toFlushAndYield(['Inner content']);
expect(ReactNoop.getChildren()).toEqual([
span('Sync'),
span('Outer content'),
span('Inner content'),
]);
});
it('renders an expiration boundary synchronously', async () => {
spyOnDev(console, 'error');
// Synchronously render a tree that suspends
ReactNoop.flushSync(() =>
ReactNoop.render(
<Fragment>
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text="Async" />
</Suspense>
<Text text="Sync" />
</Fragment>,
),
);
expect(Scheduler).toHaveYielded([
// The async child suspends
'Suspend! [Async]',
// We immediately render the fallback UI
'Loading...',
// Continue on the sibling
'Sync',
]);
// The tree commits synchronously
expect(ReactNoop.getChildren()).toEqual([span('Loading...'), span('Sync')]);
// Once the promise resolves, we render the suspended view
await resolveText('Async');
expect(Scheduler).toHaveYielded(['Promise resolved [Async]']);
expect(Scheduler).toFlushAndYield(['Async']);
expect(ReactNoop.getChildren()).toEqual([span('Async'), span('Sync')]);
});
it('suspending inside an expired expiration boundary will bubble to the next one', async () => {
ReactNoop.flushSync(() =>
ReactNoop.render(
<Fragment>
<Suspense fallback={<Text text="Loading (outer)..." />}>
<Suspense fallback={<AsyncText text="Loading (inner)..." />}>
<AsyncText text="Async" />
</Suspense>
<Text text="Sync" />
</Suspense>
</Fragment>,
),
);
expect(Scheduler).toHaveYielded([
'Suspend! [Async]',
'Suspend! [Loading (inner)...]',
'Sync',
'Loading (outer)...',
]);
// The tree commits synchronously
expect(ReactNoop.getChildren()).toEqual([span('Loading (outer)...')]);
});
it('expires early by default', async () => {
ReactNoop.render(
<Fragment>
<Suspense fallback={<Text text="Loading..." />} />
</Fragment>,
);
expect(Scheduler).toFlushAndYield([]);
ReactNoop.render(
<Fragment>
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text="Async" ms={3000} />
</Suspense>
<Text text="Sync" />
</Fragment>,
);
expect(Scheduler).toFlushAndYield([
// The async child suspends
'Suspend! [Async]',
'Loading...',
// Continue on the sibling
'Sync',
]);
// The update hasn't expired yet, so we commit nothing.
expect(ReactNoop.getChildren()).toEqual([]);
// Advance both React's virtual time and Jest's timers by enough to trigger
// the timeout, but not by enough to flush the promise or reach the true
// expiration time.
ReactNoop.expire(2000);
await advanceTimers(2000);
expect(Scheduler).toFlushWithoutYielding();
expect(ReactNoop.getChildren()).toEqual([span('Loading...'), span('Sync')]);
// Once the promise resolves, we render the suspended view
await advanceTimers(1000);
expect(Scheduler).toHaveYielded(['Promise resolved [Async]']);
expect(Scheduler).toFlushAndYield(['Async']);
expect(ReactNoop.getChildren()).toEqual([span('Async'), span('Sync')]);
});
it('resolves successfully even if fallback render is pending', async () => {
ReactNoop.render(
<>
<Suspense fallback={<Text text="Loading..." />} />
</>,
);
expect(Scheduler).toFlushAndYield([]);
expect(ReactNoop.getChildren()).toEqual([]);
ReactNoop.render(
<>
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text="Async" ms={3000} />
</Suspense>
</>,
);
expect(ReactNoop.flushNextYield()).toEqual(['Suspend! [Async]']);
await advanceTimers(1500);
expect(Scheduler).toHaveYielded([]);
expect(ReactNoop.getChildren()).toEqual([]);
// Before we have a chance to flush, the promise resolves.
await advanceTimers(2000);
expect(Scheduler).toHaveYielded(['Promise resolved [Async]']);
expect(Scheduler).toFlushAndYield([
// We've now pinged the boundary but we don't know if we should restart yet,
// because we haven't completed the suspense boundary.
'Loading...',
// Once we've completed the boundary we restarted.
'Async',
]);
expect(ReactNoop.getChildren()).toEqual([span('Async')]);
});
it('throws a helpful error when an update is suspends without a placeholder', () => {
ReactNoop.render(<AsyncText ms={1000} text="Async" />);
expect(Scheduler).toFlushAndThrow(
'AsyncText suspended while rendering, but no fallback UI was specified.',
);
});
it('a Suspense component correctly handles more than one suspended child', async () => {
ReactNoop.render(
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text="A" ms={100} />
<AsyncText text="B" ms={100} />
</Suspense>,
);
Scheduler.unstable_advanceTime(10000);
expect(Scheduler).toFlushExpired([
'Suspend! [A]',
'Suspend! [B]',
'Loading...',
]);
expect(ReactNoop.getChildren()).toEqual([span('Loading...')]);
await advanceTimers(100);
expect(Scheduler).toHaveYielded([
'Promise resolved [A]',
'Promise resolved [B]',
]);
expect(Scheduler).toFlushAndYield(['A', 'B']);
expect(ReactNoop.getChildren()).toEqual([span('A'), span('B')]);
});
it('can resume rendering earlier than a timeout', async () => {
ReactNoop.render(<Suspense fallback={<Text text="Loading..." />} />);
expect(Scheduler).toFlushAndYield([]);
ReactNoop.render(
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text="Async" ms={100} />
</Suspense>,
);
expect(Scheduler).toFlushAndYield(['Suspend! [Async]', 'Loading...']);
expect(ReactNoop.getChildren()).toEqual([]);
// Advance time by an amount slightly smaller than what's necessary to
// resolve the promise
await advanceTimers(99);
// Nothing has rendered yet
expect(Scheduler).toFlushWithoutYielding();
expect(ReactNoop.getChildren()).toEqual([]);
// Resolve the promise
await advanceTimers(1);
// We can now resume rendering
expect(Scheduler).toHaveYielded(['Promise resolved [Async]']);
expect(Scheduler).toFlushAndYield(['Async']);
expect(ReactNoop.getChildren()).toEqual([span('Async')]);
});
// @gate experimental
it('starts working on an update even if its priority falls between two suspended levels', async () => {
function App(props) {
return (
<Suspense fallback={<Text text="Loading..." />}>
{props.text === 'C' || props.text === 'S' ? (
<Text text={props.text} />
) : (
<AsyncText text={props.text} ms={10000} />
)}
</Suspense>
);
}
// First mount without suspending. This ensures we already have content
// showing so that subsequent updates will suspend.
ReactNoop.render(<App text="S" />);
expect(Scheduler).toFlushAndYield(['S']);
// Schedule an update, and suspend for up to 5 seconds.
React.unstable_startTransition(() => ReactNoop.render(<App text="A" />));
// The update should suspend.
expect(Scheduler).toFlushAndYield(['Suspend! [A]', 'Loading...']);
expect(ReactNoop.getChildren()).toEqual([span('S')]);
// Advance time until right before it expires.
await advanceTimers(4999);
ReactNoop.expire(4999);
expect(Scheduler).toFlushWithoutYielding();
expect(ReactNoop.getChildren()).toEqual([span('S')]);
// Schedule another low priority update.
React.unstable_startTransition(() => ReactNoop.render(<App text="B" />));
// This update should also suspend.
expect(Scheduler).toFlushAndYield(['Suspend! [B]', 'Loading...']);
expect(ReactNoop.getChildren()).toEqual([span('S')]);
// Schedule a regular update. Its expiration time will fall between
// the expiration times of the previous two updates.
ReactNoop.render(<App text="C" />);
expect(Scheduler).toFlushAndYield(['C']);
expect(ReactNoop.getChildren()).toEqual([span('C')]);
await advanceTimers(10000);
// Flush the remaining work.
expect(Scheduler).toHaveYielded([
'Promise resolved [A]',
'Promise resolved [B]',
]);
// Nothing else to render.
expect(Scheduler).toFlushWithoutYielding();
expect(ReactNoop.getChildren()).toEqual([span('C')]);
});
it('flushes all expired updates in a single batch', async () => {
class Foo extends React.Component {
componentDidUpdate() {
Scheduler.unstable_yieldValue('Commit: ' + this.props.text);
}