Moc window.location in Jest

Last modified: 
Tuesday, September 11th, 2018

A sketchy means to mock window.location in Jest.

describe('My Test', () => {
  const originalWindow = window;

  beforeAll(() => {
    // eslint-disable-next-line no-native-reassign
    window = jest.fn();
    window.location = { host: 'example.com' };
  });

  it('mocks window.location.host', () => {
    expect(window.location.host).toBe('example.com');
  });

  afterAll(() => {
    // eslint-disable-next-line no-native-reassign
    window = originalWindow;
  });
});


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.