Skip to content

Commit a29bd91

Browse files
committed
Create dedicated jest timer functions
The naming should indicate that they should only be called in a jest-like environment
1 parent 3108e5b commit a29bd91

File tree

1 file changed

+14
-12
lines changed

1 file changed

+14
-12
lines changed

src/helpers.js

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,15 @@ const TEXT_NODE = 3
55

66
// Currently this fn only supports jest timers, but it could support other test runners in the future.
77
function runWithRealTimers(callback) {
8-
return _runWithRealTimers(callback).callbackReturnValue
8+
// istanbul ignore else
9+
if (typeof jest !== 'undefined') {
10+
return runWithJestRealTimers(callback).callbackReturnValue
11+
}
12+
13+
return callback()
914
}
1015

11-
function _runWithRealTimers(callback) {
16+
function runWithJestRealTimers(callback) {
1217
const timerAPI = {
1318
clearImmediate,
1419
clearInterval,
@@ -18,29 +23,26 @@ function _runWithRealTimers(callback) {
1823
setTimeout,
1924
}
2025

21-
// istanbul ignore else
22-
if (typeof jest !== 'undefined') {
23-
jest.useRealTimers()
24-
}
26+
jest.useRealTimers()
2527

2628
const callbackReturnValue = callback()
2729

28-
const usedJestFakeTimers =
29-
typeof jest !== 'undefined' &&
30-
Object.entries(timerAPI).some(([name, func]) => func !== globalObj[name])
30+
const usedFakeTimers = Object.entries(timerAPI).some(
31+
([name, func]) => func !== globalObj[name],
32+
)
3133

32-
if (usedJestFakeTimers) {
34+
if (usedFakeTimers) {
3335
jest.useFakeTimers(timerAPI.setTimeout?.clock ? 'modern' : 'legacy')
3436
}
3537

3638
return {
3739
callbackReturnValue,
38-
usedJestFakeTimers,
40+
usedFakeTimers,
3941
}
4042
}
4143

4244
const jestFakeTimersAreEnabled = () =>
43-
Boolean(_runWithRealTimers(() => {}).usedJestFakeTimers)
45+
typeof jest !== 'undefined' && runWithJestRealTimers(() => {}).usedFakeTimers
4446

4547
// we only run our tests in node, and setImmediate is supported in node.
4648
// istanbul ignore next

0 commit comments

Comments
 (0)