DEV Community

tmhao2005
tmhao2005

Posted on

6 1

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay