Skip to content

Safe check for setImmediate and clearImmediate #916

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Mar 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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