/
utils.js
79 lines (67 loc) · 2.31 KB
/
utils.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
// @flow
import typeof ReactTestRenderer from 'react-test-renderer';
export function act(callback: Function): void {
const TestUtils = require('react-dom/test-utils');
TestUtils.act(() => {
callback();
});
// Flush Bridge operations
jest.runAllTimers();
}
export async function actSuspense(
callback: Function,
numTimesToFlush: number = 1
): Promise<void> {
const TestUtils = require('react-dom/test-utils');
const Scheduler = require('scheduler');
// $FlowFixMe Flow doens't know about "await act()" yet
await TestUtils.act(async () => {
callback();
// Resolve pending suspense promises
jest.runAllTimers();
});
// Run cascading microtasks and flush scheduled React work.
// Components that suspend multiple times will need to do this once per suspend operation.
// HACK Ideally the mock scheduler would provide an API to ask if there was outstanding work.
while (--numTimesToFlush >= 0) {
// $FlowFixMe Flow doens't know about "await act()" yet
await TestUtils.act(async () => {
jest.runAllTimers();
Scheduler.flushAll();
});
}
}
export function beforeEachProfiling(): void {
// Mock React's timing information so that test runs are predictable.
jest.mock('scheduler', () =>
// $FlowFixMe Flow does not konw about requireActual
require.requireActual('scheduler/unstable_mock')
);
// DevTools itself uses performance.now() to offset commit times
// so they appear relative to when profiling was started in the UI.
jest.spyOn(performance, 'now').mockImplementation(
// $FlowFixMe Flow does not konw about requireActual
require.requireActual('scheduler/unstable_mock').unstable_now
);
}
export function getRendererID(): number {
if (global.agent == null) {
throw Error('Agent unavailable.');
}
const ids = Object.keys(global.agent._rendererInterfaces);
if (ids.length !== 1) {
throw Error('Multiple renderers attached.');
}
return parseInt(ids[0], 10);
}
export function requireTestRenderer(): ReactTestRenderer {
let hook;
try {
// Hide the hook before requiring TestRenderer, so we don't end up with a loop.
hook = global.__REACT_DEVTOOLS_GLOBAL_HOOK__;
delete global.__REACT_DEVTOOLS_GLOBAL_HOOK__;
return require('react-test-renderer');
} finally {
global.__REACT_DEVTOOLS_GLOBAL_HOOK__ = hook;
}
}