'Jest 27: How to reset mock for jest.spyOn(window, "setTimeout")?
I am updating a project from jest version 26 to jest version 27. As part of the update I had to switch from assertions on setTimeout
to assertions on jest.spyOn(window, "setTimeout")
.
I want to define spy globally and reset it before each test, something like:
const timeoutSpy = jest.spyOn(window, "setTimeout");
beforeEach(() => {
jest.resetAllMocks();
});
This code doesn't work as I expected. Assertions for expect(timeoutSpy).toHaveBeenCalledTimes(n)
fail due to mismatch of expected (n) and received (0) number of calls.
What is the correct way to reset a globally defined timeoutSpy before each test?
Thank you.
Solution 1:[1]
You should use jest.restoreAllMocks().
Restores all mocks back to their original value. Equivalent to calling
.mockRestore()
on every mocked function. Beware thatjest.restoreAllMocks()
only works when the mock was created withjest.spyOn
; other mocks will require you to manually restore them.
Solution 2:[2]
Using jest.resetAllMocks();
in the beforeEach
should be sufficient. The code below can be used to prove it:
function callTimeout() {
setTimeout(() => {
console.log('hello');
})
}
const timeoutSpy = jest.spyOn(window, 'setTimeout');
describe("test timeout", () => {
beforeEach(() => {
jest.resetAllMocks();
});
it("test 1", () => {
callTimeout();
callTimeout();
expect(timeoutSpy).toHaveBeenCalledTimes(2);
})
it("test 2", () => {
callTimeout();
callTimeout();
expect(timeoutSpy).toHaveBeenCalledTimes(2);
})
});
I had to test testEnvironment
property in jest.config.js
file to jsdom
for window
variable to work. However you can replace window
to global
for it to work with the default as node
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | slideshowp2 |
Solution 2 | Ovidijus Parsiunas |