Skip to content

Commit 14788b6

Browse files
fix(timers): safe check for setImmediate and clearImmediate (#916)
Co-authored-by: Kent C. Dodds <[email protected]>
1 parent c6acb0a commit 14788b6

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

src/__tests__/helpers.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,4 +97,23 @@ describe('run with real timers', () => {
9797
})
9898
expect(global.setTimeout).toBe(fakedSetTimeout)
9999
})
100+
101+
describe('run with setImmediate and clearImmediate deleted', () => {
102+
const setImmediate = global.setImmediate
103+
const clearImmediate = global.clearImmediate
104+
105+
beforeEach(() => {
106+
delete global.setImmediate
107+
delete global.clearImmediate
108+
})
109+
110+
afterEach(() => {
111+
global.setImmediate = setImmediate
112+
global.clearImmediate = clearImmediate
113+
})
114+
115+
test('safe check for setImmediate and clearImmediate', () => {
116+
expect(() => runWithRealTimers(() => {})).not.toThrow()
117+
})
118+
})
100119
})

src/helpers.js

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,21 @@ function runWithRealTimers(callback) {
1616

1717
function runWithJestRealTimers(callback) {
1818
const timerAPI = {
19-
clearImmediate,
2019
clearInterval,
2120
clearTimeout,
22-
setImmediate,
2321
setInterval,
2422
setTimeout,
2523
}
2624

25+
// For more on why we have the check here,
26+
// checkout https://github.com/testing-library/dom-testing-library/issues/914
27+
if (typeof setImmediate === 'function') {
28+
timerAPI.setImmediate = setImmediate
29+
}
30+
if (typeof clearImmediate === 'function') {
31+
timerAPI.clearImmediate = clearImmediate
32+
}
33+
2734
jest.useRealTimers()
2835

2936
const callbackReturnValue = callback()

0 commit comments

Comments
 (0)