-
Notifications
You must be signed in to change notification settings - Fork 45.7k
/
profilingCache-test.js
808 lines (692 loc) · 22.9 KB
/
profilingCache-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
/**
* 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.
*
* @flow
*/
import typeof ReactTestRenderer from 'react-test-renderer';
import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
import type Store from 'react-devtools-shared/src/devtools/store';
describe('ProfilingCache', () => {
let PropTypes;
let React;
let ReactDOM;
let Scheduler;
let SchedulerTracing;
let TestRenderer: ReactTestRenderer;
let bridge: FrontendBridge;
let store: Store;
let utils;
beforeEach(() => {
utils = require('./utils');
utils.beforeEachProfiling();
bridge = global.bridge;
store = global.store;
store.collapseNodesByDefault = false;
store.recordChangeDescriptions = true;
PropTypes = require('prop-types');
React = require('react');
ReactDOM = require('react-dom');
Scheduler = require('scheduler');
SchedulerTracing = require('scheduler/tracing');
TestRenderer = utils.requireTestRenderer();
});
it('should collect data for each root (including ones added or mounted after profiling started)', () => {
const Parent = ({count}) => {
Scheduler.unstable_advanceTime(10);
const children = new Array(count)
.fill(true)
.map((_, index) => <Child key={index} duration={index} />);
return (
<React.Fragment>
{children}
<MemoizedChild duration={1} />
</React.Fragment>
);
};
const Child = ({duration}) => {
Scheduler.unstable_advanceTime(duration);
return null;
};
const MemoizedChild = React.memo(Child);
const containerA = document.createElement('div');
const containerB = document.createElement('div');
const containerC = document.createElement('div');
utils.act(() => ReactDOM.render(<Parent count={2} />, containerA));
utils.act(() => ReactDOM.render(<Parent count={1} />, containerB));
utils.act(() => store.profilerStore.startProfiling());
utils.act(() => ReactDOM.render(<Parent count={3} />, containerA));
utils.act(() => ReactDOM.render(<Parent count={1} />, containerC));
utils.act(() => ReactDOM.render(<Parent count={1} />, containerA));
utils.act(() => ReactDOM.unmountComponentAtNode(containerB));
utils.act(() => ReactDOM.render(<Parent count={0} />, containerA));
utils.act(() => store.profilerStore.stopProfiling());
const allProfilingDataForRoots = [];
function Validator({previousProfilingDataForRoot, rootID}) {
const profilingDataForRoot = store.profilerStore.getDataForRoot(rootID);
if (previousProfilingDataForRoot != null) {
expect(profilingDataForRoot).toEqual(previousProfilingDataForRoot);
} else {
expect(profilingDataForRoot).toMatchSnapshot(
`Data for root ${profilingDataForRoot.displayName}`,
);
}
allProfilingDataForRoots.push(profilingDataForRoot);
return null;
}
const dataForRoots =
store.profilerStore.profilingData !== null
? store.profilerStore.profilingData.dataForRoots
: null;
expect(dataForRoots).not.toBeNull();
if (dataForRoots !== null) {
dataForRoots.forEach(dataForRoot => {
utils.act(() =>
TestRenderer.create(
<Validator
previousProfilingDataForRoot={null}
rootID={dataForRoot.rootID}
/>,
),
);
});
}
expect(allProfilingDataForRoots).toHaveLength(3);
utils.exportImportHelper(bridge, store);
allProfilingDataForRoots.forEach(profilingDataForRoot => {
utils.act(() =>
TestRenderer.create(
<Validator
previousProfilingDataForRoot={profilingDataForRoot}
rootID={profilingDataForRoot.rootID}
/>,
),
);
});
});
it('should collect data for each commit', () => {
const Parent = ({count}) => {
Scheduler.unstable_advanceTime(10);
const children = new Array(count)
.fill(true)
.map((_, index) => <Child key={index} duration={index} />);
return (
<React.Fragment>
{children}
<MemoizedChild duration={1} />
</React.Fragment>
);
};
const Child = ({duration}) => {
Scheduler.unstable_advanceTime(duration);
return null;
};
const MemoizedChild = React.memo(Child);
const container = document.createElement('div');
utils.act(() => store.profilerStore.startProfiling());
utils.act(() => ReactDOM.render(<Parent count={2} />, container));
utils.act(() => ReactDOM.render(<Parent count={3} />, container));
utils.act(() => ReactDOM.render(<Parent count={1} />, container));
utils.act(() => ReactDOM.render(<Parent count={0} />, container));
utils.act(() => store.profilerStore.stopProfiling());
const allCommitData = [];
function Validator({commitIndex, previousCommitDetails, rootID}) {
const commitData = store.profilerStore.getCommitData(rootID, commitIndex);
if (previousCommitDetails != null) {
expect(commitData).toEqual(previousCommitDetails);
} else {
allCommitData.push(commitData);
expect(commitData).toMatchSnapshot(
`CommitDetails commitIndex: ${commitIndex}`,
);
}
return null;
}
const rootID = store.roots[0];
for (let commitIndex = 0; commitIndex < 4; commitIndex++) {
utils.act(() => {
TestRenderer.create(
<Validator
commitIndex={commitIndex}
previousCommitDetails={null}
rootID={rootID}
/>,
);
});
}
expect(allCommitData).toHaveLength(4);
utils.exportImportHelper(bridge, store);
for (let commitIndex = 0; commitIndex < 4; commitIndex++) {
utils.act(() => {
TestRenderer.create(
<Validator
commitIndex={commitIndex}
previousCommitDetails={allCommitData[commitIndex]}
rootID={rootID}
/>,
);
});
}
});
it('should record changed props/state/context/hooks', () => {
let instance = null;
const ModernContext = React.createContext(0);
class LegacyContextProvider extends React.Component<
any,
{|count: number|},
> {
static childContextTypes = {
count: PropTypes.number,
};
state = {count: 0};
getChildContext() {
return this.state;
}
render() {
instance = this;
return (
<ModernContext.Provider value={this.state.count}>
<React.Fragment>
<ModernContextConsumer />
<LegacyContextConsumer />
</React.Fragment>
</ModernContext.Provider>
);
}
}
const FunctionComponentWithHooks = ({count}) => {
React.useMemo(() => count, [count]);
return null;
};
class ModernContextConsumer extends React.Component<any> {
static contextType = ModernContext;
render() {
return <FunctionComponentWithHooks count={this.context} />;
}
}
class LegacyContextConsumer extends React.Component<any> {
static contextTypes = {
count: PropTypes.number,
};
render() {
return <FunctionComponentWithHooks count={this.context.count} />;
}
}
const container = document.createElement('div');
utils.act(() => store.profilerStore.startProfiling());
utils.act(() => ReactDOM.render(<LegacyContextProvider />, container));
expect(instance).not.toBeNull();
utils.act(() => (instance: any).setState({count: 1}));
utils.act(() =>
ReactDOM.render(<LegacyContextProvider foo={123} />, container),
);
utils.act(() =>
ReactDOM.render(<LegacyContextProvider bar="abc" />, container),
);
utils.act(() => ReactDOM.render(<LegacyContextProvider />, container));
utils.act(() => store.profilerStore.stopProfiling());
const allCommitData = [];
function Validator({commitIndex, previousCommitDetails, rootID}) {
const commitData = store.profilerStore.getCommitData(rootID, commitIndex);
if (previousCommitDetails != null) {
expect(commitData).toEqual(previousCommitDetails);
} else {
allCommitData.push(commitData);
expect(commitData).toMatchSnapshot(
`CommitDetails commitIndex: ${commitIndex}`,
);
}
return null;
}
const rootID = store.roots[0];
for (let commitIndex = 0; commitIndex < 5; commitIndex++) {
utils.act(() => {
TestRenderer.create(
<Validator
commitIndex={commitIndex}
previousCommitDetails={null}
rootID={rootID}
/>,
);
});
}
expect(allCommitData).toHaveLength(5);
utils.exportImportHelper(bridge, store);
for (let commitIndex = 0; commitIndex < 5; commitIndex++) {
utils.act(() => {
TestRenderer.create(
<Validator
commitIndex={commitIndex}
previousCommitDetails={allCommitData[commitIndex]}
rootID={rootID}
/>,
);
});
}
});
it('should properly detect changed hooks', () => {
const Context = React.createContext(0);
function reducer(state, action) {
switch (action.type) {
case 'invert':
return {value: !state.value};
default:
throw new Error();
}
}
let dispatch = null;
let setState = null;
const Component = ({count, string}) => {
// These hooks may change and initiate re-renders.
setState = React.useState('abc')[1];
dispatch = React.useReducer(reducer, {value: true})[1];
// This hook's return value may change between renders,
// but the hook itself isn't stateful.
React.useContext(Context);
// These hooks and their dependencies may not change between renders.
// We're using them to ensure that they don't trigger false positives.
React.useCallback(() => () => {}, [string]);
React.useMemo(() => string, [string]);
// These hooks never "change".
React.useEffect(() => {}, [string]);
React.useLayoutEffect(() => {}, [string]);
return null;
};
const container = document.createElement('div');
utils.act(() => store.profilerStore.startProfiling());
utils.act(() =>
ReactDOM.render(
<Context.Provider value={true}>
<Component count={1} />
</Context.Provider>,
container,
),
);
// Second render has no changed hooks, only changed props.
utils.act(() =>
ReactDOM.render(
<Context.Provider value={true}>
<Component count={2} />
</Context.Provider>,
container,
),
);
// Third render has a changed reducer hook
utils.act(() => dispatch({type: 'invert'}));
// Fourth render has a changed state hook
utils.act(() => setState('def'));
// Fifth render has a changed context value, but no changed hook.
// Technically, DevTools will miss this "context" change since it only tracks legacy context.
utils.act(() =>
ReactDOM.render(
<Context.Provider value={false}>
<Component count={2} />
</Context.Provider>,
container,
),
);
utils.act(() => store.profilerStore.stopProfiling());
const allCommitData = [];
function Validator({commitIndex, previousCommitDetails, rootID}) {
const commitData = store.profilerStore.getCommitData(rootID, commitIndex);
if (previousCommitDetails != null) {
expect(commitData).toEqual(previousCommitDetails);
} else {
allCommitData.push(commitData);
expect(commitData).toMatchSnapshot(
`CommitDetails commitIndex: ${commitIndex}`,
);
}
return null;
}
const rootID = store.roots[0];
for (let commitIndex = 0; commitIndex < 5; commitIndex++) {
utils.act(() => {
TestRenderer.create(
<Validator
commitIndex={commitIndex}
previousCommitDetails={null}
rootID={rootID}
/>,
);
});
}
expect(allCommitData).toHaveLength(5);
// Export and re-import profile data and make sure it is retained.
utils.exportImportHelper(bridge, store);
for (let commitIndex = 0; commitIndex < 5; commitIndex++) {
utils.act(() => {
TestRenderer.create(
<Validator
commitIndex={commitIndex}
previousCommitDetails={allCommitData[commitIndex]}
rootID={rootID}
/>,
);
});
}
});
it('should calculate a self duration based on actual children (not filtered children)', () => {
store.componentFilters = [utils.createDisplayNameFilter('^Parent$')];
const Grandparent = () => {
Scheduler.unstable_advanceTime(10);
return (
<React.Fragment>
<Parent key="one" />
<Parent key="two" />
</React.Fragment>
);
};
const Parent = () => {
Scheduler.unstable_advanceTime(2);
return <Child />;
};
const Child = () => {
Scheduler.unstable_advanceTime(1);
return null;
};
utils.act(() => store.profilerStore.startProfiling());
utils.act(() =>
ReactDOM.render(<Grandparent />, document.createElement('div')),
);
utils.act(() => store.profilerStore.stopProfiling());
let commitData = null;
function Validator({commitIndex, rootID}) {
commitData = store.profilerStore.getCommitData(rootID, commitIndex);
expect(commitData).toMatchSnapshot(
`CommitDetails with filtered self durations`,
);
return null;
}
const rootID = store.roots[0];
utils.act(() => {
TestRenderer.create(<Validator commitIndex={0} rootID={rootID} />);
});
expect(commitData).not.toBeNull();
});
it('should calculate self duration correctly for suspended views', async done => {
let data;
const getData = () => {
if (data) {
return data;
} else {
throw new Promise(resolve => {
data = 'abc';
resolve(data);
});
}
};
const Parent = () => {
Scheduler.unstable_advanceTime(10);
return (
<React.Suspense fallback={<Fallback />}>
<Async />
</React.Suspense>
);
};
const Fallback = () => {
Scheduler.unstable_advanceTime(2);
return 'Fallback...';
};
const Async = () => {
Scheduler.unstable_advanceTime(3);
return getData();
};
utils.act(() => store.profilerStore.startProfiling());
await utils.actAsync(() =>
ReactDOM.render(<Parent />, document.createElement('div')),
);
utils.act(() => store.profilerStore.stopProfiling());
const allCommitData = [];
function Validator({commitIndex, rootID}) {
const commitData = store.profilerStore.getCommitData(rootID, commitIndex);
allCommitData.push(commitData);
expect(commitData).toMatchSnapshot(
`CommitDetails with filtered self durations`,
);
return null;
}
const rootID = store.roots[0];
for (let commitIndex = 0; commitIndex < 2; commitIndex++) {
utils.act(() => {
TestRenderer.create(
<Validator commitIndex={commitIndex} rootID={rootID} />,
);
});
}
expect(allCommitData).toHaveLength(2);
done();
});
it('should collect data for each rendered fiber', () => {
const Parent = ({count}) => {
Scheduler.unstable_advanceTime(10);
const children = new Array(count)
.fill(true)
.map((_, index) => <Child key={index} duration={index} />);
return (
<React.Fragment>
{children}
<MemoizedChild duration={1} />
</React.Fragment>
);
};
const Child = ({duration}) => {
Scheduler.unstable_advanceTime(duration);
return null;
};
const MemoizedChild = React.memo(Child);
const container = document.createElement('div');
utils.act(() => store.profilerStore.startProfiling());
utils.act(() => ReactDOM.render(<Parent count={1} />, container));
utils.act(() => ReactDOM.render(<Parent count={2} />, container));
utils.act(() => ReactDOM.render(<Parent count={3} />, container));
utils.act(() => store.profilerStore.stopProfiling());
const allFiberCommits = [];
function Validator({fiberID, previousFiberCommits, rootID}) {
const fiberCommits = store.profilerStore.profilingCache.getFiberCommits({
fiberID,
rootID,
});
if (previousFiberCommits != null) {
expect(fiberCommits).toEqual(previousFiberCommits);
} else {
allFiberCommits.push(fiberCommits);
expect(fiberCommits).toMatchSnapshot(
`FiberCommits: element ${fiberID}`,
);
}
return null;
}
const rootID = store.roots[0];
for (let index = 0; index < store.numElements; index++) {
utils.act(() => {
const fiberID = store.getElementIDAtIndex(index);
if (fiberID == null) {
throw Error(`Unexpected null ID for element at index ${index}`);
}
TestRenderer.create(
<Validator
fiberID={fiberID}
previousFiberCommits={null}
rootID={rootID}
/>,
);
});
}
expect(allFiberCommits).toHaveLength(store.numElements);
utils.exportImportHelper(bridge, store);
for (let index = 0; index < store.numElements; index++) {
utils.act(() => {
const fiberID = store.getElementIDAtIndex(index);
if (fiberID == null) {
throw Error(`Unexpected null ID for element at index ${index}`);
}
TestRenderer.create(
<Validator
fiberID={fiberID}
previousFiberCommits={allFiberCommits[index]}
rootID={rootID}
/>,
);
});
}
});
it('should report every traced interaction', () => {
const Parent = ({count}) => {
Scheduler.unstable_advanceTime(10);
const children = new Array(count)
.fill(true)
.map((_, index) => <Child key={index} duration={index} />);
return (
<React.Fragment>
{children}
<MemoizedChild duration={1} />
</React.Fragment>
);
};
const Child = ({duration}) => {
Scheduler.unstable_advanceTime(duration);
return null;
};
const MemoizedChild = React.memo(Child);
const container = document.createElement('div');
utils.act(() => store.profilerStore.startProfiling());
utils.act(() =>
SchedulerTracing.unstable_trace(
'mount: one child',
Scheduler.unstable_now(),
() => ReactDOM.render(<Parent count={1} />, container),
),
);
utils.act(() =>
SchedulerTracing.unstable_trace(
'update: two children',
Scheduler.unstable_now(),
() => ReactDOM.render(<Parent count={2} />, container),
),
);
utils.act(() => store.profilerStore.stopProfiling());
let interactions = null;
function Validator({previousInteractions, rootID}) {
interactions = store.profilerStore.profilingCache.getInteractionsChartData(
{
rootID,
},
).interactions;
if (previousInteractions != null) {
expect(interactions).toEqual(previousInteractions);
} else {
expect(interactions).toMatchSnapshot('Interactions');
}
return null;
}
const rootID = store.roots[0];
utils.act(() =>
TestRenderer.create(
<Validator previousInteractions={null} rootID={rootID} />,
),
);
expect(interactions).not.toBeNull();
utils.exportImportHelper(bridge, store);
utils.act(() =>
TestRenderer.create(
<Validator previousInteractions={interactions} rootID={rootID} />,
),
);
});
it('should handle unexpectedly shallow suspense trees', () => {
const container = document.createElement('div');
utils.act(() => store.profilerStore.startProfiling());
utils.act(() => ReactDOM.render(<React.Suspense />, container));
utils.act(() => store.profilerStore.stopProfiling());
function Validator({commitIndex, rootID}) {
const profilingDataForRoot = store.profilerStore.getDataForRoot(rootID);
expect(profilingDataForRoot).toMatchSnapshot('Empty Suspense node');
return null;
}
const rootID = store.roots[0];
utils.act(() => {
TestRenderer.create(<Validator commitIndex={0} rootID={rootID} />);
});
});
// See https://github.com/facebook/react/issues/18831
it('should not crash during route transitions with Suspense', () => {
const RouterContext = React.createContext();
function App() {
return (
<Router>
<Switch>
<Route path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
</Switch>
</Router>
);
}
const Home = () => {
return (
<React.Suspense>
<Link path="/about">Home</Link>
</React.Suspense>
);
};
const About = () => <div>About</div>;
// Mimics https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Router.js
function Router({children}) {
const [path, setPath] = React.useState('/');
return (
<RouterContext.Provider value={{path, setPath}}>
{children}
</RouterContext.Provider>
);
}
// Mimics https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Switch.js
function Switch({children}) {
return (
<RouterContext.Consumer>
{context => {
let element = null;
React.Children.forEach(children, child => {
if (context.path === child.props.path) {
element = child.props.children;
}
});
return element ? React.cloneElement(element) : null;
}}
</RouterContext.Consumer>
);
}
// Mimics https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Route.js
function Route({children, path}) {
return null;
}
const linkRef = React.createRef();
// Mimics https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/Link.js
function Link({children, path}) {
return (
<RouterContext.Consumer>
{context => {
return (
<button ref={linkRef} onClick={() => context.setPath(path)}>
{children}
</button>
);
}}
</RouterContext.Consumer>
);
}
const {Simulate} = require('react-dom/test-utils');
const container = document.createElement('div');
utils.act(() => ReactDOM.render(<App />, container));
expect(container.textContent).toBe('Home');
utils.act(() => store.profilerStore.startProfiling());
utils.act(() => Simulate.click(linkRef.current));
utils.act(() => store.profilerStore.stopProfiling());
expect(container.textContent).toBe('About');
});
});