Skip to content

Commit

Permalink
fix(timers): safe check for setImmediate and clearImmediate (#916)
Browse files Browse the repository at this point in the history
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
  • Loading branch information
renatoalencar and kentcdodds committed Mar 25, 2021
1 parent c6acb0a commit 14788b6
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
19 changes: 19 additions & 0 deletions src/__tests__/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,23 @@ describe('run with real timers', () => {
})
expect(global.setTimeout).toBe(fakedSetTimeout)
})

describe('run with setImmediate and clearImmediate deleted', () => {
const setImmediate = global.setImmediate
const clearImmediate = global.clearImmediate

beforeEach(() => {
delete global.setImmediate
delete global.clearImmediate
})

afterEach(() => {
global.setImmediate = setImmediate
global.clearImmediate = clearImmediate
})

test('safe check for setImmediate and clearImmediate', () => {
expect(() => runWithRealTimers(() => {})).not.toThrow()
})
})
})
11 changes: 9 additions & 2 deletions src/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,21 @@ function runWithRealTimers(callback) {

function runWithJestRealTimers(callback) {
const timerAPI = {
clearImmediate,
clearInterval,
clearTimeout,
setImmediate,
setInterval,
setTimeout,
}

// For more on why we have the check here,
// checkout https://github.com/testing-library/dom-testing-library/issues/914
if (typeof setImmediate === 'function') {
timerAPI.setImmediate = setImmediate
}
if (typeof clearImmediate === 'function') {
timerAPI.clearImmediate = clearImmediate
}

jest.useRealTimers()

const callbackReturnValue = callback()
Expand Down

0 comments on commit 14788b6

Please sign in to comment.