-
Notifications
You must be signed in to change notification settings - Fork 273
/
Copy pathtimers.ts
95 lines (79 loc) · 2.65 KB
/
timers.ts
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
// Most content of this file sourced directly from https://github.com/testing-library/dom-testing-library/blob/main/src/helpers.js
/* globals jest */
const globalObj = typeof window === 'undefined' ? global : window;
type FakeTimersTypes = 'modern' | 'legacy';
// Currently this fn only supports jest timers, but it could support other test runners in the future.
function runWithRealTimers<T>(callback: () => T): T {
const fakeTimersType = getJestFakeTimersType();
if (fakeTimersType) {
jest.useRealTimers();
}
const callbackReturnValue = callback();
if (fakeTimersType) {
const fakeTimersConfig = getFakeTimersConfigFromType(fakeTimersType);
jest.useFakeTimers(fakeTimersConfig);
}
return callbackReturnValue;
}
function getJestFakeTimersType(): FakeTimersTypes | null {
// istanbul ignore if
if (
typeof jest === 'undefined' ||
typeof globalObj.setTimeout === 'undefined' ||
process.env.RNTL_SKIP_AUTO_DETECT_FAKE_TIMERS
) {
return null;
}
if (
// @ts-expect-error jest mutates setTimeout
typeof globalObj.setTimeout._isMockFunction !== 'undefined' &&
// @ts-expect-error jest mutates setTimeout
globalObj.setTimeout._isMockFunction
) {
return 'legacy';
}
if (
// @ts-expect-error jest mutates setTimeout
typeof globalObj.setTimeout.clock !== 'undefined' &&
typeof jest.getRealSystemTime !== 'undefined'
) {
try {
// jest.getRealSystemTime is only supported for Jest's `modern` fake timers and otherwise throws
jest.getRealSystemTime();
return 'modern';
} catch {
// not using Jest's modern fake timers
}
}
return null;
}
function getFakeTimersConfigFromType(type: FakeTimersTypes) {
return type === 'legacy' ? { legacyFakeTimers: true } : { legacyFakeTimers: false };
}
const jestFakeTimersAreEnabled = (): boolean => Boolean(getJestFakeTimersType());
// we only run our tests in node, and setImmediate is supported in node.
function setImmediatePolyfill(fn: () => void) {
return globalObj.setTimeout(fn, 0);
}
type BindTimeFunctions = {
clearTimeoutFn: typeof clearTimeout;
setImmediateFn: typeof setImmediate;
setTimeoutFn: typeof setTimeout;
};
function bindTimeFunctions(): BindTimeFunctions {
return {
clearTimeoutFn: globalObj.clearTimeout,
setImmediateFn: globalObj.setImmediate || setImmediatePolyfill,
setTimeoutFn: globalObj.setTimeout,
};
}
const { clearTimeoutFn, setImmediateFn, setTimeoutFn } = runWithRealTimers(
bindTimeFunctions,
) as BindTimeFunctions;
export {
clearTimeoutFn as clearTimeout,
jestFakeTimersAreEnabled,
runWithRealTimers,
setImmediateFn as setImmediate,
setTimeoutFn as setTimeout,
};