Jest: mock window.location.href


This post was inspired by a question from “Jest: mock window.location methods”.

How do we use Jest to mock window.location.href since it’s an accessor (getter/setter) instead of a method?

You would recreate window.location with the href getter/setter mocked.

Example

Mock the href getter:

delete window.location;
window.location = {};
const getHrefSpy = jest.fn();
Object.defineProperty(window.location, 'href', {
  get: getHrefSpy,
});

Test that href is called:

it('mocks window.location.href', () => {
  expect(getHrefSpy).not.toHaveBeenCalled();
  window.location.href;
  expect(getHrefSpy).toHaveBeenCalled();
});

Code

Full test example:

// jest-mock-window-location-href.test.js
const { location } = window;
const getHrefSpy = jest.fn(() => 'example.com');
const setHrefSpy = jest.fn(href => href);

beforeAll(() => {
  delete window.location;
  window.location = {};
  Object.defineProperty(window.location, 'href', {
    get: getHrefSpy,
    set: setHrefSpy,
  });
});

it('mocks window.location.href', () => {
  expect(getHrefSpy).not.toHaveBeenCalled();
  console.log(window.location.href);
  expect(getHrefSpy).toHaveBeenCalled();
});

afterAll(() => {
  window.location = location;
});

Demo

Repl.it:



Please support this site and join our Discord!