forked from facebook/react
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathReactSuspense-test.js
636 lines (565 loc) · 19.3 KB
/
ReactSuspense-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
let React;
let Fragment;
let ReactNoop;
let SimpleCacheProvider;
let Timeout;
let cache;
let readText;
describe('ReactSuspense', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
Fragment = React.Fragment;
ReactNoop = require('react-noop-renderer');
SimpleCacheProvider = require('simple-cache-provider');
Timeout = React.Timeout;
cache = SimpleCacheProvider.createCache();
readText = SimpleCacheProvider.createResource(([text, ms = 0]) => {
return new Promise(resolve =>
setTimeout(() => {
ReactNoop.yield(`Promise resolved [${text}]`);
resolve(text);
}, ms),
);
}, ([text, ms]) => text);
});
// function div(...children) {
// children = children.map(c => (typeof c === 'string' ? {text: c} : c));
// return {type: 'div', children, prop: undefined};
// }
function span(prop) {
return {type: 'span', children: [], prop};
}
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
return new Promise(resolve => {
setImmediate(resolve);
});
}
function Text(props) {
ReactNoop.yield(props.text);
return <span prop={props.text} />;
}
function AsyncText(props) {
const text = props.text;
try {
readText(cache, [props.text, props.ms]);
ReactNoop.yield(text);
return <span prop={text} />;
} catch (promise) {
ReactNoop.yield(`Suspend! [${text}]`);
throw promise;
}
}
function Fallback(props) {
return (
<Timeout ms={props.timeout}>
{didExpire => (didExpire ? props.placeholder : props.children)}
</Timeout>
);
}
it('suspends rendering and continues later', async () => {
function Bar(props) {
ReactNoop.yield('Bar');
return props.children;
}
function Foo() {
ReactNoop.yield('Foo');
return (
<Bar>
<AsyncText text="A" ms={100} />
<Text text="B" />
</Bar>
);
}
ReactNoop.render(<Foo />);
expect(ReactNoop.flush()).toEqual([
'Foo',
'Bar',
// A suspends
'Suspend! [A]',
// But we keep rendering the siblings
'B',
]);
expect(ReactNoop.getChildren()).toEqual([]);
// Flush some of the time
await advanceTimers(50);
// Still nothing...
expect(ReactNoop.flush()).toEqual([]);
expect(ReactNoop.getChildren()).toEqual([]);
// Flush the promise completely
await advanceTimers(50);
// Renders successfully
expect(ReactNoop.flush()).toEqual([
'Promise resolved [A]',
'Foo',
'Bar',
'A',
'B',
]);
expect(ReactNoop.getChildren()).toEqual([span('A'), span('B')]);
});
it('continues rendering siblings after suspending', async () => {
ReactNoop.render(
<Fragment>
<Text text="A" />
<AsyncText text="B" />
<Text text="C" />
<Text text="D" />
</Fragment>,
);
// B suspends. Continue rendering the remaining siblings.
expect(ReactNoop.flush()).toEqual(['A', 'Suspend! [B]', 'C', 'D']);
// Did not commit yet.
expect(ReactNoop.getChildren()).toEqual([]);
// Wait for data to resolve
await advanceTimers(100);
// Renders successfully
expect(ReactNoop.flush()).toEqual([
'Promise resolved [B]',
'A',
'B',
'C',
'D',
]);
expect(ReactNoop.getChildren()).toEqual([
span('A'),
span('B'),
span('C'),
span('D'),
]);
});
it('can update at a higher priority while in a suspended state', async () => {
function App(props) {
return (
<Fragment>
<Text text={props.highPri} />
<AsyncText text={props.lowPri} />
</Fragment>
);
}
// Initial mount
ReactNoop.render(<App highPri="A" lowPri="1" />);
ReactNoop.flush();
await advanceTimers(0);
ReactNoop.flush();
expect(ReactNoop.getChildren()).toEqual([span('A'), span('1')]);
// Update the low-pri text
ReactNoop.render(<App highPri="A" lowPri="2" />);
expect(ReactNoop.flush()).toEqual([
'A',
// Suspends
'Suspend! [2]',
]);
// 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(ReactNoop.flush()).toEqual(['B', '1']);
expect(ReactNoop.getChildren()).toEqual([span('B'), span('1')]);
// Unblock the low-pri text and finish
await advanceTimers(0);
expect(ReactNoop.flush()).toEqual(['Promise resolved [2]']);
expect(ReactNoop.getChildren()).toEqual([span('B'), span('1')]);
});
it('keeps working on lower priority work after being unblocked', async () => {
function App(props) {
return (
<Fragment>
<AsyncText text="A" />
{props.showB && <Text text="B" />}
</Fragment>
);
}
ReactNoop.render(<App showB={false} />);
expect(ReactNoop.flush()).toEqual(['Suspend! [A]']);
expect(ReactNoop.getChildren()).toEqual([]);
// Advance React's virtual time by enough to fall into a new async bucket.
ReactNoop.expire(1200);
ReactNoop.render(<App showB={true} />);
expect(ReactNoop.flush()).toEqual(['Suspend! [A]', 'B']);
expect(ReactNoop.getChildren()).toEqual([]);
await advanceTimers(0);
expect(ReactNoop.flush()).toEqual(['Promise resolved [A]', 'A', 'B']);
expect(ReactNoop.getChildren()).toEqual([span('A'), span('B')]);
});
it('coalesces all async updates when in a suspended state', async () => {
ReactNoop.render(<AsyncText text="A" />);
ReactNoop.flush();
await advanceTimers(0);
ReactNoop.flush();
expect(ReactNoop.getChildren()).toEqual([span('A')]);
ReactNoop.render(<AsyncText text="B" ms={50} />);
expect(ReactNoop.flush()).toEqual(['Suspend! [B]']);
expect(ReactNoop.getChildren()).toEqual([span('A')]);
// Advance React's virtual time so that C falls into a new expiration bucket
ReactNoop.expire(1000);
ReactNoop.render(<AsyncText text="C" ms={100} />);
expect(ReactNoop.flush()).toEqual([
// Tries C first, since it has a later expiration time
'Suspend! [C]',
// Does not retry B, because its promise has not resolved yet.
]);
expect(ReactNoop.getChildren()).toEqual([span('A')]);
// Unblock B
await advanceTimers(90);
// Even though B's promise resolved, the view is still suspended because it
// coalesced with C.
expect(ReactNoop.flush()).toEqual(['Promise resolved [B]']);
expect(ReactNoop.getChildren()).toEqual([span('A')]);
// Unblock C
await advanceTimers(50);
expect(ReactNoop.flush()).toEqual(['Promise resolved [C]', 'C']);
expect(ReactNoop.getChildren()).toEqual([span('C')]);
});
it('forces an expiration after an update times out', async () => {
ReactNoop.render(
<Fragment>
<Fallback placeholder={<Text text="Loading..." />}>
<AsyncText text="Async" ms={20000} />
</Fallback>
<Text text="Sync" />
</Fragment>,
);
expect(ReactNoop.flush()).toEqual([
// The async child suspends
'Suspend! [Async]',
// 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);
expect(ReactNoop.flushExpired()).toEqual([
// Still suspended.
'Suspend! [Async]',
// Now that the update has expired, we render the fallback UI
'Loading...',
'Sync',
]);
expect(ReactNoop.getChildren()).toEqual([span('Loading...'), span('Sync')]);
// Once the promise resolves, we render the suspended view
await advanceTimers(10000);
expect(ReactNoop.flush()).toEqual(['Promise resolved [Async]', 'Async']);
expect(ReactNoop.getChildren()).toEqual([span('Async'), span('Sync')]);
});
it('renders an expiration boundary synchronously', async () => {
// Synchronously render a tree that suspends
ReactNoop.flushSync(() =>
ReactNoop.render(
<Fragment>
<Fallback placeholder={<Text text="Loading..." />}>
<AsyncText text="Async" />
</Fallback>
<Text text="Sync" />
</Fragment>,
),
);
expect(ReactNoop.clearYields()).toEqual([
// 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 advanceTimers(0);
expect(ReactNoop.flush()).toEqual(['Promise resolved [Async]', '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>
<Fallback placeholder={<Text text="Loading (outer)..." />}>
<Fallback placeholder={<AsyncText text="Loading (inner)..." />}>
<AsyncText text="Async" />
</Fallback>
<Text text="Sync" />
</Fallback>
</Fragment>,
),
);
expect(ReactNoop.clearYields()).toEqual([
'Suspend! [Async]',
'Suspend! [Loading (inner)...]',
'Sync',
'Loading (outer)...',
]);
// The tree commits synchronously
expect(ReactNoop.getChildren()).toEqual([span('Loading (outer)...')]);
});
it('expires early with a `timeout` option', async () => {
ReactNoop.render(
<Fragment>
<Fallback timeout={100} placeholder={<Text text="Loading..." />}>
<AsyncText text="Async" ms={1000} />
</Fallback>
<Text text="Sync" />
</Fragment>,
);
expect(ReactNoop.flush()).toEqual([
// The async child suspends
'Suspend! [Async]',
// 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(120);
await advanceTimers(120);
expect(ReactNoop.flush()).toEqual([
// Still suspended.
'Suspend! [Async]',
// Now that the expiration view has timed out, we render the fallback UI
'Loading...',
'Sync',
]);
expect(ReactNoop.getChildren()).toEqual([span('Loading...'), span('Sync')]);
// Once the promise resolves, we render the suspended view
await advanceTimers(1000);
expect(ReactNoop.flush()).toEqual(['Promise resolved [Async]', 'Async']);
expect(ReactNoop.getChildren()).toEqual([span('Async'), span('Sync')]);
});
it('throws a helpful error when a synchronous update is suspended', () => {
expect(() => {
ReactNoop.flushSync(() => ReactNoop.render(<AsyncText text="Async" />));
}).toThrow(
'A synchronous update was suspended, but no fallback UI was provided.',
);
});
it('throws a helpful error when an expired update is suspended', async () => {
ReactNoop.render(<AsyncText text="Async" ms={20000} />);
expect(ReactNoop.flush()).toEqual(['Suspend! [Async]']);
await advanceTimers(10000);
ReactNoop.expire(10000);
expect(() => {
expect(ReactNoop.flush()).toEqual(['Suspend! [Async]']);
}).toThrow(
'An update was suspended for longer than the timeout, but no fallback ' +
'UI was provided.',
);
});
it('a Timeout component correctly handles more than one suspended child', async () => {
ReactNoop.render(
<Fallback timeout={0}>
<AsyncText text="A" ms={100} />
<AsyncText text="B" ms={100} />
</Fallback>,
);
ReactNoop.expire(10000);
expect(ReactNoop.flush()).toEqual(['Suspend! [A]', 'Suspend! [B]']);
expect(ReactNoop.getChildren()).toEqual([]);
await advanceTimers(100);
expect(ReactNoop.flush()).toEqual([
'Promise resolved [A]',
'Promise resolved [B]',
'A',
'B',
]);
expect(ReactNoop.getChildren()).toEqual([span('A'), span('B')]);
});
it('can resume rendering earlier than a timeout', async () => {
ReactNoop.render(
<Fallback timeout={1000} placeholder={<Text text="Loading..." />}>
<AsyncText text="Async" ms={100} />
</Fallback>,
);
expect(ReactNoop.flush()).toEqual(['Suspend! [Async]']);
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(ReactNoop.flush()).toEqual([]);
expect(ReactNoop.getChildren()).toEqual([]);
// Resolve the promise
await advanceTimers(1);
// We can now resume rendering
expect(ReactNoop.flush()).toEqual(['Promise resolved [Async]', 'Async']);
expect(ReactNoop.getChildren()).toEqual([span('Async')]);
});
describe('splitting a high-pri update into high and low', () => {
React = require('react');
class AsyncValue extends React.Component {
state = {asyncValue: this.props.defaultValue};
componentDidMount() {
ReactNoop.deferredUpdates(() => {
this.setState((state, props) => ({asyncValue: props.value}));
});
}
componentDidUpdate() {
if (this.props.value !== this.state.asyncValue) {
ReactNoop.deferredUpdates(() => {
this.setState((state, props) => ({asyncValue: props.value}));
});
}
}
render() {
return this.props.children(this.state.asyncValue);
}
}
it('coalesces async values when in a suspended state', async () => {
function App(props) {
const highPriText = props.text;
return (
<AsyncValue value={highPriText} defaultValue={null}>
{lowPriText => (
<Fragment>
<Text text={`High-pri: ${highPriText}`} />
{lowPriText && (
<AsyncText text={`Low-pri: ${lowPriText}`} ms={100} />
)}
</Fragment>
)}
</AsyncValue>
);
}
function renderAppSync(props) {
ReactNoop.flushSync(() => ReactNoop.render(<App {...props} />));
}
// Initial mount
renderAppSync({text: 'A'});
expect(ReactNoop.flush()).toEqual([
// First we render at high priority
'High-pri: A',
// Then we come back later to render a low priority
'High-pri: A',
// The low-pri view suspends
'Suspend! [Low-pri: A]',
]);
expect(ReactNoop.getChildren()).toEqual([span('High-pri: A')]);
// Partially flush the promise for 'A', not by enough to resolve it.
await advanceTimers(99);
// Advance React's virtual time so that the next update falls into a new
// expiration bucket
ReactNoop.expire(2000);
// Update to B. At this point, the low-pri view still hasn't updated
// to 'A'.
renderAppSync({text: 'B'});
expect(ReactNoop.flush()).toEqual([
// First we render at high priority
'High-pri: B',
// Then we come back later to render a low priority
'High-pri: B',
// The low-pri view suspends
'Suspend! [Low-pri: B]',
]);
expect(ReactNoop.getChildren()).toEqual([span('High-pri: B')]);
// Flush the rest of the promise for 'A', without flushing the one
// for 'B'.
await advanceTimers(1);
expect(ReactNoop.flush()).toEqual([
// A is unblocked
'Promise resolved [Low-pri: A]',
// But we don't try to render it, because there's a lower priority
// update that is also suspended.
]);
expect(ReactNoop.getChildren()).toEqual([span('High-pri: B')]);
// Flush the remaining work.
await advanceTimers(99);
expect(ReactNoop.flush()).toEqual([
// B is unblocked
'Promise resolved [Low-pri: B]',
// Now we can continue rendering the async view
'High-pri: B',
'Low-pri: B',
]);
expect(ReactNoop.getChildren()).toEqual([
span('High-pri: B'),
span('Low-pri: B'),
]);
});
});
describe('a Delay component', () => {
function Never() {
// Throws a promise that resolves after some arbitrarily large
// number of seconds. The idea is that this component will never
// resolve. It's always wrapped by a Timeout.
throw new Promise(resolve => setTimeout(() => resolve(), 10000));
}
function Delay({ms}) {
return (
<Timeout ms={ms}>
{didTimeout => {
if (didTimeout) {
// Once ms has elapsed, render null. This allows the rest of the
// tree to resume rendering.
return null;
}
return <Never />;
}}
</Timeout>
);
}
function DebouncedText({text, ms}) {
return (
<Fragment>
<Delay ms={ms} />
<Text text={text} />
</Fragment>
);
}
it('works', async () => {
ReactNoop.render(<DebouncedText text="A" ms={1000} />);
ReactNoop.flush();
expect(ReactNoop.getChildren()).toEqual([]);
await advanceTimers(999);
ReactNoop.expire(999);
ReactNoop.flush();
expect(ReactNoop.getChildren()).toEqual([]);
await advanceTimers(1);
ReactNoop.expire(1);
ReactNoop.flush();
expect(ReactNoop.getChildren()).toEqual([span('A')]);
});
it('uses the most recent update as its start time', async () => {
ReactNoop.render(<DebouncedText text="A" ms={1000} />);
ReactNoop.flush();
expect(ReactNoop.getChildren()).toEqual([]);
// Advance time by a little, but not by enough to move this into a new
// expiration bucket.
await advanceTimers(10);
ReactNoop.expire(10);
ReactNoop.flush();
expect(ReactNoop.getChildren()).toEqual([]);
// Schedule an update. It should have the same expiration as the first one.
ReactNoop.render(<DebouncedText text="B" ms={1000} />);
// Advance time by enough that it would have timed-out the first update,
// but not enough that it times out the second one.
await advanceTimers(999);
ReactNoop.expire(999);
ReactNoop.flush();
expect(ReactNoop.getChildren()).toEqual([]);
// Advance time by just a bit more to trigger the timeout.
await advanceTimers(1);
ReactNoop.expire(1);
ReactNoop.flush();
expect(ReactNoop.getChildren()).toEqual([span('B')]);
});
});
// TODO:
// Timeout inside an async boundary
// Start time of expiration bucket is time of most recent update
// Promise rejection
// Warns if promise reaches the root
// Multiple timeouts with different values
// Suspending inside an offscreen tree
// Timeout for CPU-bound work
});