/
ReactMemo-test.js
501 lines (446 loc) · 15.8 KB
/
ReactMemo-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
/**
* 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
*/
/* eslint-disable no-func-assign */
'use strict';
let PropTypes;
let React;
let ReactNoop;
let Suspense;
let Scheduler;
describe('memo', () => {
beforeEach(() => {
jest.resetModules();
PropTypes = require('prop-types');
React = require('react');
ReactNoop = require('react-noop-renderer');
Scheduler = require('scheduler');
({Suspense} = React);
});
function span(prop) {
return {type: 'span', children: [], prop, hidden: false};
}
function Text(props) {
Scheduler.unstable_yieldValue(props.text);
return <span prop={props.text} />;
}
async function fakeImport(result) {
return {default: result};
}
it('warns when giving a ref (simple)', async () => {
// This test lives outside sharedTests because the wrappers don't forward
// refs properly, and they end up affecting the current owner which is used
// by the warning (making the messages not line up).
function App() {
return null;
}
App = React.memo(App);
function Outer() {
return <App ref={() => {}} />;
}
ReactNoop.render(<Outer />);
expect(() => expect(Scheduler).toFlushWithoutYielding()).toErrorDev([
'Warning: Function components cannot be given refs. Attempts to access ' +
'this ref will fail.',
]);
});
it('warns when giving a ref (complex)', async () => {
// defaultProps means this won't use SimpleMemoComponent (as of this writing)
// SimpleMemoComponent is unobservable tho, so we can't check :)
function App() {
return null;
}
App.defaultProps = {};
App = React.memo(App);
function Outer() {
return <App ref={() => {}} />;
}
ReactNoop.render(<Outer />);
expect(() => expect(Scheduler).toFlushWithoutYielding()).toErrorDev([
'Warning: Function components cannot be given refs. Attempts to access ' +
'this ref will fail.',
]);
});
// Tests should run against both the lazy and non-lazy versions of `memo`.
// To make the tests work for both versions, we wrap the non-lazy version in
// a lazy function component.
sharedTests('normal', (...args) => {
const Memo = React.memo(...args);
function Indirection(props) {
return <Memo {...props} />;
}
return React.lazy(() => fakeImport(Indirection));
});
sharedTests('lazy', (...args) => {
const Memo = React.memo(...args);
return React.lazy(() => fakeImport(Memo));
});
function sharedTests(label, memo) {
describe(`${label}`, () => {
it('bails out on props equality', async () => {
function Counter({count}) {
return <Text text={count} />;
}
Counter = memo(Counter);
ReactNoop.render(
<Suspense fallback={<Text text="Loading..." />}>
<Counter count={0} />
</Suspense>,
);
expect(Scheduler).toFlushAndYield(['Loading...']);
await Promise.resolve();
expect(Scheduler).toFlushAndYield([0]);
expect(ReactNoop.getChildren()).toEqual([span(0)]);
// Should bail out because props have not changed
ReactNoop.render(
<Suspense>
<Counter count={0} />
</Suspense>,
);
expect(Scheduler).toFlushAndYield([]);
expect(ReactNoop.getChildren()).toEqual([span(0)]);
// Should update because count prop changed
ReactNoop.render(
<Suspense>
<Counter count={1} />
</Suspense>,
);
expect(Scheduler).toFlushAndYield([1]);
expect(ReactNoop.getChildren()).toEqual([span(1)]);
});
it("does not bail out if there's a context change", async () => {
const CountContext = React.createContext(0);
function readContext(Context) {
const dispatcher =
React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
.ReactCurrentDispatcher.current;
return dispatcher.readContext(Context);
}
function Counter(props) {
const count = readContext(CountContext);
return <Text text={`${props.label}: ${count}`} />;
}
Counter = memo(Counter);
class Parent extends React.Component {
state = {count: 0};
render() {
return (
<Suspense fallback={<Text text="Loading..." />}>
<CountContext.Provider value={this.state.count}>
<Counter label="Count" />
</CountContext.Provider>
</Suspense>
);
}
}
const parent = React.createRef(null);
ReactNoop.render(<Parent ref={parent} />);
expect(Scheduler).toFlushAndYield(['Loading...']);
await Promise.resolve();
expect(Scheduler).toFlushAndYield(['Count: 0']);
expect(ReactNoop.getChildren()).toEqual([span('Count: 0')]);
// Should bail out because props have not changed
ReactNoop.render(<Parent ref={parent} />);
expect(Scheduler).toFlushAndYield([]);
expect(ReactNoop.getChildren()).toEqual([span('Count: 0')]);
// Should update because there was a context change
parent.current.setState({count: 1});
expect(Scheduler).toFlushAndYield(['Count: 1']);
expect(ReactNoop.getChildren()).toEqual([span('Count: 1')]);
});
it('accepts custom comparison function', async () => {
function Counter({count}) {
return <Text text={count} />;
}
Counter = memo(Counter, (oldProps, newProps) => {
Scheduler.unstable_yieldValue(
`Old count: ${oldProps.count}, New count: ${newProps.count}`,
);
return oldProps.count === newProps.count;
});
ReactNoop.render(
<Suspense fallback={<Text text="Loading..." />}>
<Counter count={0} />
</Suspense>,
);
expect(Scheduler).toFlushAndYield(['Loading...']);
await Promise.resolve();
expect(Scheduler).toFlushAndYield([0]);
expect(ReactNoop.getChildren()).toEqual([span(0)]);
// Should bail out because props have not changed
ReactNoop.render(
<Suspense>
<Counter count={0} />
</Suspense>,
);
expect(Scheduler).toFlushAndYield(['Old count: 0, New count: 0']);
expect(ReactNoop.getChildren()).toEqual([span(0)]);
// Should update because count prop changed
ReactNoop.render(
<Suspense>
<Counter count={1} />
</Suspense>,
);
expect(Scheduler).toFlushAndYield(['Old count: 0, New count: 1', 1]);
expect(ReactNoop.getChildren()).toEqual([span(1)]);
});
it('supports non-pure class components', async () => {
class CounterInner extends React.Component {
static defaultProps = {suffix: '!'};
render() {
return <Text text={this.props.count + '' + this.props.suffix} />;
}
}
const Counter = memo(CounterInner);
ReactNoop.render(
<Suspense fallback={<Text text="Loading..." />}>
<Counter count={0} />
</Suspense>,
);
expect(Scheduler).toFlushAndYield(['Loading...']);
await Promise.resolve();
expect(Scheduler).toFlushAndYield(['0!']);
expect(ReactNoop.getChildren()).toEqual([span('0!')]);
// Should bail out because props have not changed
ReactNoop.render(
<Suspense>
<Counter count={0} />
</Suspense>,
);
expect(Scheduler).toFlushAndYield([]);
expect(ReactNoop.getChildren()).toEqual([span('0!')]);
// Should update because count prop changed
ReactNoop.render(
<Suspense>
<Counter count={1} />
</Suspense>,
);
expect(Scheduler).toFlushAndYield(['1!']);
expect(ReactNoop.getChildren()).toEqual([span('1!')]);
});
it('supports defaultProps defined on the memo() return value', async () => {
function Counter({a, b, c, d, e}) {
return <Text text={a + b + c + d + e} />;
}
Counter.defaultProps = {
a: 1,
};
// Note! We intentionally use React.memo() rather than the injected memo().
// This tests a synchronous chain of React.memo() without lazy() in the middle.
Counter = React.memo(Counter);
Counter.defaultProps = {
b: 2,
};
Counter = React.memo(Counter);
Counter = React.memo(Counter); // Layer without defaultProps
Counter.defaultProps = {
c: 3,
};
Counter = React.memo(Counter);
Counter.defaultProps = {
d: 4,
};
// The final layer uses memo() from test fixture (which might be lazy).
Counter = memo(Counter);
ReactNoop.render(
<Suspense fallback={<Text text="Loading..." />}>
<Counter e={5} />
</Suspense>,
);
expect(Scheduler).toFlushAndYield(['Loading...']);
await Promise.resolve();
expect(Scheduler).toFlushAndYield([15]);
expect(ReactNoop.getChildren()).toEqual([span(15)]);
// Should bail out because props have not changed
ReactNoop.render(
<Suspense>
<Counter e={5} />
</Suspense>,
);
expect(Scheduler).toFlushAndYield([]);
expect(ReactNoop.getChildren()).toEqual([span(15)]);
// Should update because count prop changed
ReactNoop.render(
<Suspense>
<Counter e={10} />
</Suspense>,
);
expect(Scheduler).toFlushAndYield([20]);
expect(ReactNoop.getChildren()).toEqual([span(20)]);
});
it('warns if the first argument is undefined', () => {
expect(() =>
memo(),
).toErrorDev(
'memo: The first argument must be a component. Instead ' +
'received: undefined',
{withoutStack: true},
);
});
it('warns if the first argument is null', () => {
expect(() =>
memo(null),
).toErrorDev(
'memo: The first argument must be a component. Instead ' +
'received: null',
{withoutStack: true},
);
});
it('validates propTypes declared on the inner component', () => {
function FnInner(props) {
return props.inner;
}
FnInner.propTypes = {inner: PropTypes.number.isRequired};
const Fn = React.memo(FnInner);
// Mount
expect(() => {
ReactNoop.render(<Fn inner="2" />);
expect(Scheduler).toFlushWithoutYielding();
}).toErrorDev(
'Invalid prop `inner` of type `string` supplied to `FnInner`, expected `number`.',
);
// Update
expect(() => {
ReactNoop.render(<Fn inner={false} />);
expect(Scheduler).toFlushWithoutYielding();
}).toErrorDev(
'Invalid prop `inner` of type `boolean` supplied to `FnInner`, expected `number`.',
);
});
it('validates propTypes declared on the outer component', () => {
function FnInner(props) {
return props.outer;
}
const Fn = React.memo(FnInner);
Fn.propTypes = {outer: PropTypes.number.isRequired};
// Mount
expect(() => {
ReactNoop.render(<Fn outer="3" />);
expect(Scheduler).toFlushWithoutYielding();
}).toErrorDev(
// Outer props are checked in createElement
'Invalid prop `outer` of type `string` supplied to `FnInner`, expected `number`.',
);
// Update
expect(() => {
ReactNoop.render(<Fn outer={false} />);
expect(Scheduler).toFlushWithoutYielding();
}).toErrorDev(
// Outer props are checked in createElement
'Invalid prop `outer` of type `boolean` supplied to `FnInner`, expected `number`.',
);
});
it('validates nested propTypes declarations', () => {
function Inner(props) {
return props.inner + props.middle + props.outer;
}
Inner.propTypes = {inner: PropTypes.number.isRequired};
Inner.defaultProps = {inner: 0};
const Middle = React.memo(Inner);
Middle.propTypes = {middle: PropTypes.number.isRequired};
Middle.defaultProps = {middle: 0};
const Outer = React.memo(Middle);
Outer.propTypes = {outer: PropTypes.number.isRequired};
Outer.defaultProps = {outer: 0};
// No warning expected because defaultProps satisfy both.
ReactNoop.render(
<div>
<Outer />
</div>,
);
expect(Scheduler).toFlushWithoutYielding();
// Mount
expect(() => {
ReactNoop.render(
<div>
<Outer inner="2" middle="3" outer="4" />
</div>,
);
expect(Scheduler).toFlushWithoutYielding();
}).toErrorDev([
'Invalid prop `outer` of type `string` supplied to `Inner`, expected `number`.',
'Invalid prop `middle` of type `string` supplied to `Inner`, expected `number`.',
'Invalid prop `inner` of type `string` supplied to `Inner`, expected `number`.',
]);
// Update
expect(() => {
ReactNoop.render(
<div>
<Outer inner={false} middle={false} outer={false} />
</div>,
);
expect(Scheduler).toFlushWithoutYielding();
}).toErrorDev([
'Invalid prop `outer` of type `boolean` supplied to `Inner`, expected `number`.',
'Invalid prop `middle` of type `boolean` supplied to `Inner`, expected `number`.',
'Invalid prop `inner` of type `boolean` supplied to `Inner`, expected `number`.',
]);
});
it('does not drop lower priority state updates when bailing out at higher pri (simple)', async () => {
const {useState} = React;
let setCounter;
const Counter = memo(() => {
const [counter, _setCounter] = useState(0);
setCounter = _setCounter;
return counter;
});
function App() {
return (
<Suspense fallback="Loading...">
<Counter />
</Suspense>
);
}
const root = ReactNoop.createRoot();
await ReactNoop.act(async () => {
root.render(<App />);
});
expect(root).toMatchRenderedOutput('0');
await ReactNoop.act(async () => {
setCounter(1);
ReactNoop.discreteUpdates(() => {
root.render(<App />);
});
});
expect(root).toMatchRenderedOutput('1');
});
it('does not drop lower priority state updates when bailing out at higher pri (complex)', async () => {
const {useState} = React;
let setCounter;
const Counter = memo(
() => {
const [counter, _setCounter] = useState(0);
setCounter = _setCounter;
return counter;
},
(a, b) => a.complexProp.val === b.complexProp.val,
);
function App() {
return (
<Suspense fallback="Loading...">
<Counter complexProp={{val: 1}} />
</Suspense>
);
}
const root = ReactNoop.createRoot();
await ReactNoop.act(async () => {
root.render(<App />);
});
expect(root).toMatchRenderedOutput('0');
await ReactNoop.act(async () => {
setCounter(1);
ReactNoop.discreteUpdates(() => {
root.render(<App />);
});
});
expect(root).toMatchRenderedOutput('1');
});
});
}
});