DEV Community 👩‍💻👨‍💻

tmhao2005
tmhao2005

Posted on

Tip! Mock jsdom location with Jest

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';
Enter fullscreen mode Exit fullscreen mode

You would receive an warning like below in case of jest running through above code:

Error: Not implemented: navigation (except hash changes)
Enter fullscreen mode Exit fullscreen mode

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');
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.