Problem
In some cases, we have to call assign
method of window.location
object in order to redirect to a different url as below:
window.location.assign = '/home';
You would receive an warning like below in case of jest
running through above code:
Error: Not implemented: navigation (except hash changes)
What is the solution here?
We obviously think about how to mock the location, right?
Here is the easiest way to do that:
const mockWinAssign = jest.fn();
const oldWindowLocation = window.location;
beforeAll(() => {
delete window.location;
window.location = Object.defineProperties(
{},
{
...Object.getOwnPropertyDescriptors(oldWindowLocation),
assign: {
configurable: true,
value: mockWinAssign,
},
},
)
})
afterAll(() => {
// restore location
window.location = oldWindowLocation;
})
test('your test to call location method', () => {
// do things
// finally
expect(mockWinAssign).toHaveBeenCalledWith('/home');
})
Top comments (0)