-
Notifications
You must be signed in to change notification settings - Fork 47.9k
/
Copy pathReactHooks-test.internal.js
1995 lines (1758 loc) · 60.2 KB
/
ReactHooks-test.internal.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
/**
* 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 React;
let ReactFeatureFlags;
let ReactTestRenderer;
let Scheduler;
let ReactDOMServer;
let act;
// Additional tests can be found in ReactHooksWithNoopRenderer. Plan is to
// gradually migrate those to this file.
describe('ReactHooks', () => {
beforeEach(() => {
jest.resetModules();
ReactFeatureFlags = require('shared/ReactFeatureFlags');
React = require('react');
ReactTestRenderer = require('react-test-renderer');
Scheduler = require('scheduler');
ReactDOMServer = require('react-dom/server');
act = ReactTestRenderer.unstable_concurrentAct;
});
if (__DEV__) {
// useDebugValue is a DEV-only hook
it('useDebugValue throws when used in a class component', () => {
class Example extends React.Component {
render() {
React.useDebugValue('abc');
return null;
}
}
expect(() => {
ReactTestRenderer.create(<Example />);
}).toThrow(
'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen' +
' for one of the following reasons:\n' +
'1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
'2. You might be breaking the Rules of Hooks\n' +
'3. You might have more than one copy of React in the same app\n' +
'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.',
);
});
}
it('bails out in the render phase if all of the state is the same', () => {
const {useState, useLayoutEffect} = React;
function Child({text}) {
Scheduler.unstable_yieldValue('Child: ' + text);
return text;
}
let setCounter1;
let setCounter2;
function Parent() {
const [counter1, _setCounter1] = useState(0);
setCounter1 = _setCounter1;
const [counter2, _setCounter2] = useState(0);
setCounter2 = _setCounter2;
const text = `${counter1}, ${counter2}`;
Scheduler.unstable_yieldValue(`Parent: ${text}`);
useLayoutEffect(() => {
Scheduler.unstable_yieldValue(`Effect: ${text}`);
});
return <Child text={text} />;
}
const root = ReactTestRenderer.create(null, {unstable_isConcurrent: true});
root.update(<Parent />);
expect(Scheduler).toFlushAndYield([
'Parent: 0, 0',
'Child: 0, 0',
'Effect: 0, 0',
]);
expect(root).toMatchRenderedOutput('0, 0');
// Normal update
act(() => {
setCounter1(1);
setCounter2(1);
});
expect(Scheduler).toHaveYielded([
'Parent: 1, 1',
'Child: 1, 1',
'Effect: 1, 1',
]);
// Update that bails out.
act(() => setCounter1(1));
expect(Scheduler).toHaveYielded(['Parent: 1, 1']);
// This time, one of the state updates but the other one doesn't. So we
// can't bail out.
act(() => {
setCounter1(1);
setCounter2(2);
});
expect(Scheduler).toHaveYielded([
'Parent: 1, 2',
'Child: 1, 2',
'Effect: 1, 2',
]);
// Lots of updates that eventually resolve to the current values.
act(() => {
setCounter1(9);
setCounter2(3);
setCounter1(4);
setCounter2(7);
setCounter1(1);
setCounter2(2);
});
// Because the final values are the same as the current values, the
// component bails out.
expect(Scheduler).toHaveYielded(['Parent: 1, 2']);
// prepare to check SameValue
act(() => {
setCounter1(0 / -1);
setCounter2(NaN);
});
expect(Scheduler).toHaveYielded([
'Parent: 0, NaN',
'Child: 0, NaN',
'Effect: 0, NaN',
]);
// check if re-setting to negative 0 / NaN still bails out
act(() => {
setCounter1(0 / -1);
setCounter2(NaN);
setCounter2(Infinity);
setCounter2(NaN);
});
expect(Scheduler).toHaveYielded(['Parent: 0, NaN']);
// check if changing negative 0 to positive 0 does not bail out
act(() => {
setCounter1(0);
});
expect(Scheduler).toHaveYielded([
'Parent: 0, NaN',
'Child: 0, NaN',
'Effect: 0, NaN',
]);
});
it('bails out in render phase if all the state is the same and props bail out with memo', () => {
const {useState, memo} = React;
function Child({text}) {
Scheduler.unstable_yieldValue('Child: ' + text);
return text;
}
let setCounter1;
let setCounter2;
function Parent({theme}) {
const [counter1, _setCounter1] = useState(0);
setCounter1 = _setCounter1;
const [counter2, _setCounter2] = useState(0);
setCounter2 = _setCounter2;
const text = `${counter1}, ${counter2} (${theme})`;
Scheduler.unstable_yieldValue(`Parent: ${text}`);
return <Child text={text} />;
}
Parent = memo(Parent);
const root = ReactTestRenderer.create(null, {unstable_isConcurrent: true});
root.update(<Parent theme="light" />);
expect(Scheduler).toFlushAndYield([
'Parent: 0, 0 (light)',
'Child: 0, 0 (light)',
]);
expect(root).toMatchRenderedOutput('0, 0 (light)');
// Normal update
act(() => {
setCounter1(1);
setCounter2(1);
});
expect(Scheduler).toHaveYielded([
'Parent: 1, 1 (light)',
'Child: 1, 1 (light)',
]);
// Update that bails out.
act(() => setCounter1(1));
expect(Scheduler).toHaveYielded(['Parent: 1, 1 (light)']);
// This time, one of the state updates but the other one doesn't. So we
// can't bail out.
act(() => {
setCounter1(1);
setCounter2(2);
});
expect(Scheduler).toHaveYielded([
'Parent: 1, 2 (light)',
'Child: 1, 2 (light)',
]);
// Updates bail out, but component still renders because props
// have changed
act(() => {
setCounter1(1);
setCounter2(2);
root.update(<Parent theme="dark" />);
});
expect(Scheduler).toHaveYielded([
'Parent: 1, 2 (dark)',
'Child: 1, 2 (dark)',
]);
// Both props and state bail out
act(() => {
setCounter1(1);
setCounter2(2);
root.update(<Parent theme="dark" />);
});
expect(Scheduler).toHaveYielded(['Parent: 1, 2 (dark)']);
});
it('warns about setState second argument', () => {
const {useState} = React;
let setCounter;
function Counter() {
const [counter, _setCounter] = useState(0);
setCounter = _setCounter;
Scheduler.unstable_yieldValue(`Count: ${counter}`);
return counter;
}
const root = ReactTestRenderer.create(null, {unstable_isConcurrent: true});
root.update(<Counter />);
expect(Scheduler).toFlushAndYield(['Count: 0']);
expect(root).toMatchRenderedOutput('0');
expect(() => {
act(() =>
setCounter(1, () => {
throw new Error('Expected to ignore the callback.');
}),
);
}).toErrorDev(
'State updates from the useState() and useReducer() Hooks ' +
"don't support the second callback argument. " +
'To execute a side effect after rendering, ' +
'declare it in the component body with useEffect().',
{withoutStack: true},
);
expect(Scheduler).toHaveYielded(['Count: 1']);
expect(root).toMatchRenderedOutput('1');
});
it('warns about dispatch second argument', () => {
const {useReducer} = React;
let dispatch;
function Counter() {
const [counter, _dispatch] = useReducer((s, a) => a, 0);
dispatch = _dispatch;
Scheduler.unstable_yieldValue(`Count: ${counter}`);
return counter;
}
const root = ReactTestRenderer.create(null, {unstable_isConcurrent: true});
root.update(<Counter />);
expect(Scheduler).toFlushAndYield(['Count: 0']);
expect(root).toMatchRenderedOutput('0');
expect(() => {
act(() =>
dispatch(1, () => {
throw new Error('Expected to ignore the callback.');
}),
);
}).toErrorDev(
'State updates from the useState() and useReducer() Hooks ' +
"don't support the second callback argument. " +
'To execute a side effect after rendering, ' +
'declare it in the component body with useEffect().',
{withoutStack: true},
);
expect(Scheduler).toHaveYielded(['Count: 1']);
expect(root).toMatchRenderedOutput('1');
});
it('never bails out if context has changed', () => {
const {useState, useLayoutEffect, useContext} = React;
const ThemeContext = React.createContext('light');
let setTheme;
function ThemeProvider({children}) {
const [theme, _setTheme] = useState('light');
Scheduler.unstable_yieldValue('Theme: ' + theme);
setTheme = _setTheme;
return (
<ThemeContext.Provider value={theme}>{children}</ThemeContext.Provider>
);
}
function Child({text}) {
Scheduler.unstable_yieldValue('Child: ' + text);
return text;
}
let setCounter;
function Parent() {
const [counter, _setCounter] = useState(0);
setCounter = _setCounter;
const theme = useContext(ThemeContext);
const text = `${counter} (${theme})`;
Scheduler.unstable_yieldValue(`Parent: ${text}`);
useLayoutEffect(() => {
Scheduler.unstable_yieldValue(`Effect: ${text}`);
});
return <Child text={text} />;
}
const root = ReactTestRenderer.create(null, {unstable_isConcurrent: true});
act(() => {
root.update(
<ThemeProvider>
<Parent />
</ThemeProvider>,
);
});
expect(Scheduler).toHaveYielded([
'Theme: light',
'Parent: 0 (light)',
'Child: 0 (light)',
'Effect: 0 (light)',
]);
expect(root).toMatchRenderedOutput('0 (light)');
// Updating the theme to the same value doesn't cause the consumers
// to re-render.
setTheme('light');
expect(Scheduler).toFlushAndYield([]);
expect(root).toMatchRenderedOutput('0 (light)');
// Normal update
act(() => setCounter(1));
expect(Scheduler).toHaveYielded([
'Parent: 1 (light)',
'Child: 1 (light)',
'Effect: 1 (light)',
]);
expect(root).toMatchRenderedOutput('1 (light)');
// Update that doesn't change state, so it bails out
act(() => setCounter(1));
expect(Scheduler).toHaveYielded(['Parent: 1 (light)']);
expect(root).toMatchRenderedOutput('1 (light)');
// Update that doesn't change state, but the context changes, too, so it
// can't bail out
act(() => {
setCounter(1);
setTheme('dark');
});
expect(Scheduler).toHaveYielded([
'Theme: dark',
'Parent: 1 (dark)',
'Child: 1 (dark)',
'Effect: 1 (dark)',
]);
expect(root).toMatchRenderedOutput('1 (dark)');
});
it('can bail out without calling render phase (as an optimization) if queue is known to be empty', () => {
const {useState, useLayoutEffect} = React;
function Child({text}) {
Scheduler.unstable_yieldValue('Child: ' + text);
return text;
}
let setCounter;
function Parent() {
const [counter, _setCounter] = useState(0);
setCounter = _setCounter;
Scheduler.unstable_yieldValue('Parent: ' + counter);
useLayoutEffect(() => {
Scheduler.unstable_yieldValue('Effect: ' + counter);
});
return <Child text={counter} />;
}
const root = ReactTestRenderer.create(null, {unstable_isConcurrent: true});
root.update(<Parent />);
expect(Scheduler).toFlushAndYield(['Parent: 0', 'Child: 0', 'Effect: 0']);
expect(root).toMatchRenderedOutput('0');
// Normal update
act(() => setCounter(1));
expect(Scheduler).toHaveYielded(['Parent: 1', 'Child: 1', 'Effect: 1']);
expect(root).toMatchRenderedOutput('1');
// Update to the same state. React doesn't know if the queue is empty
// because the alternate fiber has pending update priority, so we have to
// enter the render phase before we can bail out. But we bail out before
// rendering the child, and we don't fire any effects.
act(() => setCounter(1));
expect(Scheduler).toHaveYielded(['Parent: 1']);
expect(root).toMatchRenderedOutput('1');
// Update to the same state again. This times, neither fiber has pending
// update priority, so we can bail out before even entering the render phase.
act(() => setCounter(1));
expect(Scheduler).toFlushAndYield([]);
expect(root).toMatchRenderedOutput('1');
// This changes the state to something different so it renders normally.
act(() => setCounter(2));
expect(Scheduler).toHaveYielded(['Parent: 2', 'Child: 2', 'Effect: 2']);
expect(root).toMatchRenderedOutput('2');
// prepare to check SameValue
act(() => {
setCounter(0);
});
expect(Scheduler).toHaveYielded(['Parent: 0', 'Child: 0', 'Effect: 0']);
expect(root).toMatchRenderedOutput('0');
// Update to the same state for the first time to flush the queue
act(() => {
setCounter(0);
});
expect(Scheduler).toHaveYielded(['Parent: 0']);
expect(root).toMatchRenderedOutput('0');
// Update again to the same state. Should bail out.
act(() => {
setCounter(0);
});
expect(Scheduler).toFlushAndYield([]);
expect(root).toMatchRenderedOutput('0');
// Update to a different state (positive 0 to negative 0)
act(() => {
setCounter(0 / -1);
});
expect(Scheduler).toHaveYielded(['Parent: 0', 'Child: 0', 'Effect: 0']);
expect(root).toMatchRenderedOutput('0');
});
it('bails out multiple times in a row without entering render phase', () => {
const {useState} = React;
function Child({text}) {
Scheduler.unstable_yieldValue('Child: ' + text);
return text;
}
let setCounter;
function Parent() {
const [counter, _setCounter] = useState(0);
setCounter = _setCounter;
Scheduler.unstable_yieldValue('Parent: ' + counter);
return <Child text={counter} />;
}
const root = ReactTestRenderer.create(null, {unstable_isConcurrent: true});
root.update(<Parent />);
expect(Scheduler).toFlushAndYield(['Parent: 0', 'Child: 0']);
expect(root).toMatchRenderedOutput('0');
const update = value => {
setCounter(previous => {
Scheduler.unstable_yieldValue(
`Compute state (${previous} -> ${value})`,
);
return value;
});
};
ReactTestRenderer.unstable_batchedUpdates(() => {
update(0);
update(0);
update(0);
update(1);
update(2);
update(3);
});
expect(Scheduler).toHaveYielded([
// The first four updates were eagerly computed, because the queue is
// empty before each one.
'Compute state (0 -> 0)',
'Compute state (0 -> 0)',
'Compute state (0 -> 0)',
// The fourth update doesn't bail out
'Compute state (0 -> 1)',
// so subsequent updates can't be eagerly computed.
]);
// Now let's enter the render phase
expect(Scheduler).toFlushAndYield([
// We don't need to re-compute the first four updates. Only the final two.
'Compute state (1 -> 2)',
'Compute state (2 -> 3)',
'Parent: 3',
'Child: 3',
]);
expect(root).toMatchRenderedOutput('3');
});
it('can rebase on top of a previously skipped update', () => {
const {useState} = React;
function Child({text}) {
Scheduler.unstable_yieldValue('Child: ' + text);
return text;
}
let setCounter;
function Parent() {
const [counter, _setCounter] = useState(1);
setCounter = _setCounter;
Scheduler.unstable_yieldValue('Parent: ' + counter);
return <Child text={counter} />;
}
const root = ReactTestRenderer.create(null, {unstable_isConcurrent: true});
root.update(<Parent />);
expect(Scheduler).toFlushAndYield(['Parent: 1', 'Child: 1']);
expect(root).toMatchRenderedOutput('1');
const update = compute => {
setCounter(previous => {
const value = compute(previous);
Scheduler.unstable_yieldValue(
`Compute state (${previous} -> ${value})`,
);
return value;
});
};
// Update at normal priority
ReactTestRenderer.unstable_batchedUpdates(() => update(n => n * 100));
// The new state is eagerly computed.
expect(Scheduler).toHaveYielded(['Compute state (1 -> 100)']);
// but before it's flushed, a higher priority update interrupts it.
root.unstable_flushSync(() => {
update(n => n + 5);
});
expect(Scheduler).toHaveYielded([
// The eagerly computed state was completely skipped
'Compute state (1 -> 6)',
'Parent: 6',
'Child: 6',
]);
expect(root).toMatchRenderedOutput('6');
// Now when we finish the first update, the second update is rebased on top.
// Notice we didn't have to recompute the first update even though it was
// skipped in the previous render.
expect(Scheduler).toFlushAndYield([
'Compute state (100 -> 105)',
'Parent: 105',
'Child: 105',
]);
expect(root).toMatchRenderedOutput('105');
});
it('warns about variable number of dependencies', () => {
const {useLayoutEffect} = React;
function App(props) {
useLayoutEffect(() => {
Scheduler.unstable_yieldValue(
'Did commit: ' + props.dependencies.join(', '),
);
}, props.dependencies);
return props.dependencies;
}
const root = ReactTestRenderer.create(<App dependencies={['A']} />);
expect(Scheduler).toHaveYielded(['Did commit: A']);
expect(() => {
root.update(<App dependencies={['A', 'B']} />);
}).toErrorDev([
'Warning: The final argument passed to useLayoutEffect changed size ' +
'between renders. The order and size of this array must remain ' +
'constant.\n\n' +
'Previous: [A]\n' +
'Incoming: [A, B]\n',
]);
});
it('warns if switching from dependencies to no dependencies', () => {
const {useMemo} = React;
function App({text, hasDeps}) {
const resolvedText = useMemo(
() => {
Scheduler.unstable_yieldValue('Compute');
return text.toUpperCase();
},
hasDeps ? null : [text],
);
return resolvedText;
}
const root = ReactTestRenderer.create(null);
root.update(<App text="Hello" hasDeps={true} />);
expect(Scheduler).toHaveYielded(['Compute']);
expect(root).toMatchRenderedOutput('HELLO');
expect(() => {
root.update(<App text="Hello" hasDeps={false} />);
}).toErrorDev([
'Warning: useMemo received a final argument during this render, but ' +
'not during the previous render. Even though the final argument is ' +
'optional, its type cannot change between renders.',
]);
});
it('warns if deps is not an array', () => {
const {useEffect, useLayoutEffect, useMemo, useCallback} = React;
function App(props) {
useEffect(() => {}, props.deps);
useLayoutEffect(() => {}, props.deps);
useMemo(() => {}, props.deps);
useCallback(() => {}, props.deps);
return null;
}
expect(() => {
act(() => {
ReactTestRenderer.create(<App deps={'hello'} />);
});
}).toErrorDev([
'Warning: useEffect received a final argument that is not an array (instead, received `string`). ' +
'When specified, the final argument must be an array.',
'Warning: useLayoutEffect received a final argument that is not an array (instead, received `string`). ' +
'When specified, the final argument must be an array.',
'Warning: useMemo received a final argument that is not an array (instead, received `string`). ' +
'When specified, the final argument must be an array.',
'Warning: useCallback received a final argument that is not an array (instead, received `string`). ' +
'When specified, the final argument must be an array.',
]);
expect(() => {
act(() => {
ReactTestRenderer.create(<App deps={100500} />);
});
}).toErrorDev([
'Warning: useEffect received a final argument that is not an array (instead, received `number`). ' +
'When specified, the final argument must be an array.',
'Warning: useLayoutEffect received a final argument that is not an array (instead, received `number`). ' +
'When specified, the final argument must be an array.',
'Warning: useMemo received a final argument that is not an array (instead, received `number`). ' +
'When specified, the final argument must be an array.',
'Warning: useCallback received a final argument that is not an array (instead, received `number`). ' +
'When specified, the final argument must be an array.',
]);
expect(() => {
act(() => {
ReactTestRenderer.create(<App deps={{}} />);
});
}).toErrorDev([
'Warning: useEffect received a final argument that is not an array (instead, received `object`). ' +
'When specified, the final argument must be an array.',
'Warning: useLayoutEffect received a final argument that is not an array (instead, received `object`). ' +
'When specified, the final argument must be an array.',
'Warning: useMemo received a final argument that is not an array (instead, received `object`). ' +
'When specified, the final argument must be an array.',
'Warning: useCallback received a final argument that is not an array (instead, received `object`). ' +
'When specified, the final argument must be an array.',
]);
act(() => {
ReactTestRenderer.create(<App deps={[]} />);
ReactTestRenderer.create(<App deps={null} />);
ReactTestRenderer.create(<App deps={undefined} />);
});
});
it('warns if deps is not an array for useImperativeHandle', () => {
const {useImperativeHandle} = React;
const App = React.forwardRef((props, ref) => {
useImperativeHandle(ref, () => {}, props.deps);
return null;
});
expect(() => {
ReactTestRenderer.create(<App deps={'hello'} />);
}).toErrorDev([
'Warning: useImperativeHandle received a final argument that is not an array (instead, received `string`). ' +
'When specified, the final argument must be an array.',
]);
ReactTestRenderer.create(<App deps={[]} />);
ReactTestRenderer.create(<App deps={null} />);
ReactTestRenderer.create(<App deps={undefined} />);
});
it('assumes useEffect clean-up function is either a function or undefined', () => {
const {useLayoutEffect} = React;
function App(props) {
useLayoutEffect(() => {
return props.return;
});
return null;
}
const root1 = ReactTestRenderer.create(null);
expect(() => root1.update(<App return={17} />)).toErrorDev([
'Warning: An effect function must not return anything besides a ' +
'function, which is used for clean-up. You returned: 17',
]);
const root2 = ReactTestRenderer.create(null);
expect(() => root2.update(<App return={null} />)).toErrorDev([
'Warning: An effect function must not return anything besides a ' +
'function, which is used for clean-up. You returned null. If your ' +
'effect does not require clean up, return undefined (or nothing).',
]);
const root3 = ReactTestRenderer.create(null);
expect(() => root3.update(<App return={Promise.resolve()} />)).toErrorDev([
'Warning: An effect function must not return anything besides a ' +
'function, which is used for clean-up.\n\n' +
'It looks like you wrote useEffect(async () => ...) or returned a Promise.',
]);
// Error on unmount because React assumes the value is a function
expect(() => {
root3.update(null);
}).toThrow('is not a function');
});
it('does not forget render phase useState updates inside an effect', () => {
const {useState, useEffect} = React;
function Counter() {
const [counter, setCounter] = useState(0);
if (counter === 0) {
setCounter(x => x + 1);
setCounter(x => x + 1);
}
useEffect(() => {
setCounter(x => x + 1);
setCounter(x => x + 1);
}, []);
return counter;
}
const root = ReactTestRenderer.create(null);
act(() => {
root.update(<Counter />);
});
expect(root).toMatchRenderedOutput('4');
});
it('does not forget render phase useReducer updates inside an effect with hoisted reducer', () => {
const {useReducer, useEffect} = React;
const reducer = x => x + 1;
function Counter() {
const [counter, increment] = useReducer(reducer, 0);
if (counter === 0) {
increment();
increment();
}
useEffect(() => {
increment();
increment();
}, []);
return counter;
}
const root = ReactTestRenderer.create(null);
act(() => {
root.update(<Counter />);
});
expect(root).toMatchRenderedOutput('4');
});
it('does not forget render phase useReducer updates inside an effect with inline reducer', () => {
const {useReducer, useEffect} = React;
function Counter() {
const [counter, increment] = useReducer(x => x + 1, 0);
if (counter === 0) {
increment();
increment();
}
useEffect(() => {
increment();
increment();
}, []);
return counter;
}
const root = ReactTestRenderer.create(null);
act(() => {
root.update(<Counter />);
});
expect(root).toMatchRenderedOutput('4');
});
it('warns for bad useImperativeHandle first arg', () => {
const {useImperativeHandle} = React;
function App() {
useImperativeHandle({
focus() {},
});
return null;
}
expect(() => {
expect(() => {
ReactTestRenderer.create(<App />);
}).toThrow('create is not a function');
}).toErrorDev([
'Expected useImperativeHandle() first argument to either be a ' +
'ref callback or React.createRef() object. ' +
'Instead received: an object with keys {focus}.',
'Expected useImperativeHandle() second argument to be a function ' +
'that creates a handle. Instead received: undefined.',
]);
});
it('warns for bad useImperativeHandle second arg', () => {
const {useImperativeHandle} = React;
const App = React.forwardRef((props, ref) => {
useImperativeHandle(ref, {
focus() {},
});
return null;
});
expect(() => {
ReactTestRenderer.create(<App />);
}).toErrorDev([
'Expected useImperativeHandle() second argument to be a function ' +
'that creates a handle. Instead received: object.',
]);
});
// https://github.com/facebook/react/issues/14022
it('works with ReactDOMServer calls inside a component', () => {
const {useState} = React;
function App(props) {
const markup1 = ReactDOMServer.renderToString(<p>hello</p>);
const markup2 = ReactDOMServer.renderToStaticMarkup(<p>bye</p>);
const [counter] = useState(0);
return markup1 + counter + markup2;
}
const root = ReactTestRenderer.create(<App />);
expect(root.toJSON()).toMatchSnapshot();
});
it("throws when calling hooks inside .memo's compare function", () => {
const {useState} = React;
function App() {
useState(0);
return null;
}
const MemoApp = React.memo(App, () => {
useState(0);
return false;
});
const root = ReactTestRenderer.create(<MemoApp />);
// trying to render again should trigger comparison and throw
expect(() => root.update(<MemoApp />)).toThrow(
'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
' one of the following reasons:\n' +
'1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
'2. You might be breaking the Rules of Hooks\n' +
'3. You might have more than one copy of React in the same app\n' +
'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.',
);
// the next round, it does a fresh mount, so should render
expect(() => root.update(<MemoApp />)).not.toThrow(
'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
' one of the following reasons:\n' +
'1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
'2. You might be breaking the Rules of Hooks\n' +
'3. You might have more than one copy of React in the same app\n' +
'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.',
);
// and then again, fail
expect(() => root.update(<MemoApp />)).toThrow(
'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
' one of the following reasons:\n' +
'1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
'2. You might be breaking the Rules of Hooks\n' +
'3. You might have more than one copy of React in the same app\n' +
'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.',
);
});
it('warns when calling hooks inside useMemo', () => {
const {useMemo, useState} = React;
function App() {
useMemo(() => {
useState(0);
});
return null;
}
expect(() => ReactTestRenderer.create(<App />)).toErrorDev(
'Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks.',
);
});
it('warns when reading context inside useMemo', () => {
const {useMemo, createContext} = React;
const ReactCurrentDispatcher =
React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
.ReactCurrentDispatcher;
const ThemeContext = createContext('light');
function App() {
return useMemo(() => {
return ReactCurrentDispatcher.current.readContext(ThemeContext);
}, []);
}
expect(() => ReactTestRenderer.create(<App />)).toErrorDev(
'Context can only be read while React is rendering',
);
});
it('warns when reading context inside useMemo after reading outside it', () => {
const {useMemo, createContext} = React;
const ReactCurrentDispatcher =
React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
.ReactCurrentDispatcher;
const ThemeContext = createContext('light');
let firstRead, secondRead;
function App() {
firstRead = ReactCurrentDispatcher.current.readContext(ThemeContext);
useMemo(() => {});
secondRead = ReactCurrentDispatcher.current.readContext(ThemeContext);
return useMemo(() => {
return ReactCurrentDispatcher.current.readContext(ThemeContext);
}, []);
}
expect(() => ReactTestRenderer.create(<App />)).toErrorDev(
'Context can only be read while React is rendering',
);
expect(firstRead).toBe('light');
expect(secondRead).toBe('light');
});
// Throws because there's no runtime cost for being strict here.
it('throws when reading context inside useEffect', () => {
const {useEffect, createContext} = React;
const ReactCurrentDispatcher =
React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
.ReactCurrentDispatcher;
const ThemeContext = createContext('light');
function App() {
useEffect(() => {
ReactCurrentDispatcher.current.readContext(ThemeContext);
});
return null;
}