179

Currently, I am implementing unit tests for my project and there is a file that contains window.location.href.

I want to mock this to test and here is my sample code:

it("method A should work correctly", () => {
      const url = "http://dummy.com";
      Object.defineProperty(window.location, "href", {
        value: url,
        writable: true
      });
      const data = {
        id: "123",
        name: null
      };
      window.location.href = url;
      wrapper.vm.methodA(data);
      expect(window.location.href).toEqual(url);
    });

But I get this error:

TypeError: Cannot redefine property: href
        at Function.defineProperty (<anonymous>)

How should I resolve it?

3

22 Answers 22

196

You can try:

window = Object.create(window);
const url = "http://dummy.com";
Object.defineProperty(window, 'location', {
  value: {
    href: url
  },
  writable: true // possibility to override
});
expect(window.location.href).toEqual(url);  

Have a look at the Jest Issue for that problem:
Jest Issue

2
  • 13
    For me using global didn't work, I removed global. and I also needed to add writable: true otherwise once set the other tests can't change it.
    – xbmono
    Nov 22, 2020 at 22:00
  • 2
    typerror: location is not rewritable Dec 14, 2022 at 21:53
118

2020 Update


Basic

The URL object has a lot of the same functionality as the Location object. In other words, it includes properties such as pathname, search, hostname, etc. So for most cases, you can do the following:

delete window.location
window.location = new URL('https://www.example.com')

Advanced

You can also mock Location methods that you might need, which don't exist on the URL interface:

const location = new URL('https://www.example.com')
location.assign = jest.fn()
location.replace = jest.fn()
location.reload = jest.fn()

delete window.location
window.location = location
10
  • 36
    with typescript update, delete window.location will trigger an error The operand of a 'delete' operator must be optional
    – dshun
    Sep 8, 2020 at 17:11
  • 7
    Add // @ts-ignore above the line delete window.location; if you must
    – Tom
    Nov 29, 2020 at 20:35
  • 14
    Reflect.deleteProperty(global.window, 'location') deals with that without ts error
    – JCQuintas
    May 12, 2021 at 23:54
  • 9
    To get around that TS error you can do delete (window as any).location;
    – MkMan
    Jun 30, 2021 at 23:56
  • 2
    Why the window.location should be deleted? Can't it override it by window.location = location only? Apr 21, 2022 at 12:26
48

I have resolved this issue by adding writable: true and move it to beforeEach

Here is my sample code:

global.window = Object.create(window);
const url = "http://dummy.com";
Object.defineProperty(window, "location", {
    value: {
       href: url
    },
    writable: true
});
3
  • 2
    This solution also works for overwriting window.location.hostname in Jest tests. I needed writable: true in order to change the hostname more than once.
    – Jay
    Sep 24, 2019 at 14:51
  • this helps me a lot Jan 22, 2020 at 7:01
  • This is what I was looking for. Best solution for me. Oct 26, 2021 at 14:37
25

Solution for 2019 from GitHub:

delete global.window.location;
global.window = Object.create(window);
global.window.location = {
  port: '123',
  protocol: 'http:',
  hostname: 'localhost',
};
2
  • 1
    This is the only one that seems to work for me and with a helpful reason why! :) Oct 8, 2019 at 14:08
  • It works, but breaks following tests using postMessage that needs the original location.host property May 7, 2021 at 17:36
21

The best is probably to create a new URL instance, so that it parses your string like location.href does, and so it updates all the properties of location like .hash, .search, .protocol etc.

it("method A should work correctly", () => {
  const url = "http://dummy.com/";
  Object.defineProperty(window, "location", {
    value: new URL(url)
  } );

  window.location.href = url;
  expect(window.location.href).toEqual(url);

  window.location.href += "#bar"
  expect(window.location.hash).toEqual("#bar");
});

https://repl.it/repls/VoluminousHauntingFunctions

14

Working example with @testing-library/react in 2020 for window.location.assign:

  afterEach(cleanup)
  beforeEach(() => {
    Object.defineProperty(window, 'location', {
      writable: true,
      value: { assign: jest.fn() }
    })
  })
1
  • 3
    writable: true was necessary for my unit tests to work otherwise the subsequent tests wouldn't be able to overwrite it to something else. Thanks
    – xbmono
    Nov 22, 2020 at 21:58
12

Many of the examples provided doesn't mock the properties of the original Location object.

What I do is just replace Location object (window.location) by URL, because URL contains the same properties as Location object like "href", "search", "hash", "host".

Setters and Getters also work exactly like the Location object.

Example:

const realLocation = window.location;

describe('My test', () => {

    afterEach(() => {
        window.location = realLocation;
    });

    test('My test func', () => {

        // @ts-ignore
        delete window.location;

        // @ts-ignore
        window.location = new URL('http://google.com');

        console.log(window.location.href);

        // ...
    });
});
3
  • 1
    I wonder if it shouldn't be const realLocation = Object.assign({}, window.location); since I feel just assigning it directly would be passing a reference which is later overwritten. Thoughts?
    – wlh
    Mar 9, 2021 at 17:38
  • The object that the original window.location points to is not mutated in this code -- the window.location property has different objects set inside it. Since there's no mutation of the original window object, there's no need to clone it.
    – RobW
    Jul 19, 2021 at 21:42
  • @ts-ignore should not be abused if you want to use TS, it is generally a bad practice. Mar 23 at 12:52
5

TS in 2022

const orgLocation: Location = window.location;

beforeEach(() => {
  delete (window as any).location;
  window.location = (new URL("http://localhost") as any);
  window.location.assign = ({configurable:true, value:jest.fn()} as any);
  window.location.replace = ({configurable:true, value:jest.fn()} as any);
  window.location.reload = ({configurable:true, value:jest.fn()} as any);
});

afterAll(() => window.location = orgLocation);
4

Extending @jabacchetta's solution to avoid this setting bleeding into other tests:

describe("Example", () => {
  let location;

  beforeEach(() => {
    const url = "https://example.com";
    location = window.location;
    const mockLocation = new URL(url);
    mockLocation.replace = jest.fn();
    delete window.location;
    window.location = mockLocation;
  });

  afterEach(() => {
    window.location = location;
  });
});
0
4

you can try jest-location-mock.

npm install --save-dev jest-location-mock

update jest configs at jest.config.js file or jest prop inside package.json:

setupFilesAfterEnv: [ "./config/jest-setup.js" ]

create jest-setup.js

import "jest-location-mock";

usage:

it("should call assign with a relative url", () => {
    window.location.assign("/relative-url");
    expect(window.location).not.toBeAt("/");
    expect(window.location).toBeAt("/relative-url");
});
3

How to reassign window.location in your code base; the simplest working setup we found for our Jest tests:

const realLocation = window.location;

beforeEach(() => {
  delete window.location;
});

afterEach(() => {
  window.location = realLocation;
});
2

You can try a helper:

const setURL = url => global.jsdom.reconfigure({url});

describe('Test current location', () => {
  test('with GET parameter', () => {
    setURL('https://test.com?foo=bar');
    // ...your test here
  });
});
2

I use the following way using the Jest's mocking mechanism (jest.spyOn()) instead of directly overwriting the object property.

describe("...", () => {
  beforeEach(() => {
    const originalLocation = window.location;
    jest.spyOn(window, "location", "get").mockImplementation(() => ({
      ...originalLocation,
      href: "http://dummy.com", // Mock window.location.href here.
    }))
  });
  afterEach(() => {
    jest.restoreAllMocks()
  });

  it("...", () => {
    // ...
  })
});

I learned it from this post.

1

This is valid for Jest + TypeScript + Next.js (in case you use useRoute().push

const oldWindowLocation = window.location;

beforeAll(() => {
  delete window.location;
  window.location = { ...oldWindowLocation, assign: jest.fn() };
});

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

JSDOM Version

Another method, using JSDOM, which will provide window.location.href and all of the other properties of window.location, (e.g. window.location.search to get query string parameters).

import { JSDOM } from 'jsdom';

...

const { window } = new JSDOM('', {
    url: 'https://localhost/?testParam=true'
});
delete global.window;
global.window = Object.create(window);
1

I could not find how to test that window.location.href has been set with correct value AND test that window.location.replace() has been called with right params, but I tried this and it seems perfect.

    const mockWindowLocationReplace = jest.fn()
    const mockWindowLocationHref = jest.fn()
    
    const mockWindowLocation = {}
    Object.defineProperties(mockWindowLocation, {
      replace: {
        value: mockWindowLocationReplace,
        writable: false
      },
      href : {
        set: mockWindowLocationHref
      }
    })
    jest.spyOn(window, "location", "get").mockReturnValue(mockWindowLocation as Location)

    describe("my test suite", () => {
        // ...
        expect(mockWindowLocationReplace).toHaveBeenCalledWith('foo')
        expect(mockWindowLocationHref).toHaveBeenCalledWith('bar')
    })
0

Based on examples above and in other threads, here is a concrete example using jest that might help someone:

describe('Location tests', () => {
    const originalLocation = window.location;

    const mockWindowLocation = (newLocation) => {
        delete window.location;
        window.location = newLocation;
    };

    const setLocation = (path) =>
        mockWindowLocation(
            new URL(`https://example.com${path}`)
        );

    afterEach(() => {
        // Restore window.location to not destroy other tests
        mockWindowLocation(originalLocation);
    });

    it('should mock window.location successfully', () => {
        setLocation('/private-path');

        expect(window.location.href).toEqual(
            `https://example.com/private-path`
        );
    });
});
2
  • Is deleting window.location necessary? Mar 23 at 12:58
  • Honestly, I don’t remember why a delete ended up being needed there. I guess you can try without it, and if it works then happy times!
    – Bazze
    Mar 24 at 14:11
0

Probably irrelevant. But for those seeking a solution for window.open('url', attribute) I applied this, with help of some comments above:

window = Object.create(window);
const url = 'https://www.9gag.com';
Object.defineProperty(window, 'open', { value: url });

expect(window.open).toEqual(url);
0

Here's a simple one you can use in a beforeEach or ala carte per test.

It utilizes the Javascript window.history and its pushState method to manipulate the URL.

window.history.pushState({}, 'Enter Page Title Here', '/test-page.html?query=value');
1
  • can this approach cause side effects in other tests? Your code looks simple and straightforward. But I'm hesitant to apply it, and I prefer to mock window.location before tests and restore the original window.location after the tests. Like for example in this answer. Just because I'm sure that it will not affect my other tests in an unpredictable way. Jun 14 at 9:41
0

Simple and clean way to do it:

 Object.defineProperty(window, "location", {
    value: new URL("http://example.com"),
    configurable: true,
  });
0

I've fixed this issue by re-implementing window.location & window.history: https://gist.github.com/tkrotoff/52f4a29e919445d6e97f9a9e44ada449

It's heavily inspired by https://github.com/jestjs/jest/issues/5124#issuecomment-792768806 (thx sanek306) and firefox-devtools window-navigation.js (thx gregtatum & julienw)

It comes with unit tests and it works well with our source base.

You can then use window.location in your tests like you would expect:

it('should ...', () => {
  window.location.pathname = '/product/308072';

  render(<MyComponent />);

  const link = screen.getByRole<HTMLAnchorElement>('link', { name: 'Show more' });
  expect(link.href).toBe('http://localhost:3000/product/308072/more');
});

it('should ...', () => {
  const assignSpy = vi.spyOn(window.location, 'assign');

  render(<MyComponent />);

  const input = screen.getByRole<HTMLInputElement>('searchbox');
  fireEvent.change(input, { target: { value: 'My Search Query' } });
  fireEvent.submit(input);

  expect(assignSpy).toHaveBeenCalledTimes(1);
  expect(assignSpy).toHaveBeenNthCalledWith(1, '/search?query=My+Search+Query');

  assignSpy.mockRestore();
});

Here the implementation (copy-pasted from the gist, more details in the gist):

/* eslint-disable unicorn/no-null */

/*
 * Resetting window.location between tests is unfortunately a hard topic with JSDOM.
 *
 * https://gist.github.com/tkrotoff/52f4a29e919445d6e97f9a9e44ada449
 *
 * FIXME JSDOM leaves the history in place after every test, so the history will be dirty.
 * Also its implementations for window.location and window.history are lacking.
 * - https://github.com/jsdom/jsdom/blob/22.1.0/lib/jsdom/living/window/Location-impl.js
 * - https://github.com/jsdom/jsdom/blob/22.1.0/lib/jsdom/living/window/History-impl.js
 * - https://github.com/jsdom/jsdom/blob/22.1.0/lib/jsdom/living/window/SessionHistory.js
 *
 * What about Happy DOM? Implementations are empty:
 * - https://github.com/capricorn86/happy-dom/blob/v12.10.3/packages/happy-dom/src/location/Location.ts
 * - https://github.com/capricorn86/happy-dom/blob/v12.10.3/packages/happy-dom/src/history/History.ts
 *
 *
 * window.location and window.history should work together:
 * window.history should update the location, and changing the location should push a new state in the history
 *
 * Solution: re-implement window.location and window.history
 * The code is synchronous instead of asynchronous, yet it fires "popstate" events
 *
 * Inspired by:
 * - https://github.com/jestjs/jest/issues/5124#issuecomment-792768806
 * - https://github.com/firefox-devtools/profiler/blob/f894531be77dee00bb641f49a657b072183ec1fa/src/test/fixtures/mocks/window-navigation.js
 *
 *
 * Related issues:
 * - https://github.com/jestjs/jest/issues/5124
 * - https://github.com/jestjs/jest/issues/890
 * - https://github.com/jestjs/jest/issues/5987
 * - https://stackoverflow.com/q/54021037
 *
 * - Huge hope on jsdom.reconfigure() (tried by patching Vitest JSDOM env), doesn't work
 *   https://github.com/vitest-dev/vitest/discussions/2383
 *   https://github.com/simon360/jest-environment-jsdom-global/blob/v4.0.0/environment.js
 *   https://github.com/simon360/jest-environment-jsdom-global/blob/v4.0.0/README.md#using-jsdom-in-your-test-suite
 */

class WindowLocationMock implements Location {
  private url: URL;

  internalSetURLFromHistory(newURL: string | URL) {
    this.url = new URL(newURL, this.url);
  }

  constructor(url: string) {
    this.url = new URL(url);
  }

  toString() {
    return this.url.toString();
  }

  readonly ancestorOrigins = [] as unknown as DOMStringList;

  get href() {
    return this.url.toString();
  }
  set href(newUrl) {
    this.assign(newUrl);
  }

  get origin() {
    return this.url.origin;
  }

  get protocol() {
    return this.url.protocol;
  }
  set protocol(v) {
    const newUrl = new URL(this.url);
    newUrl.protocol = v;
    this.assign(newUrl);
  }

  get host() {
    return this.url.host;
  }
  set host(v) {
    const newUrl = new URL(this.url);
    newUrl.host = v;
    this.assign(newUrl);
  }

  get hostname() {
    return this.url.hostname;
  }
  set hostname(v) {
    const newUrl = new URL(this.url);
    newUrl.hostname = v;
    this.assign(newUrl);
  }

  get port() {
    return this.url.port;
  }
  set port(v) {
    const newUrl = new URL(this.url);
    newUrl.port = v;
    this.assign(newUrl);
  }

  get pathname() {
    return this.url.pathname;
  }
  set pathname(v) {
    const newUrl = new URL(this.url);
    newUrl.pathname = v;
    this.assign(newUrl);
  }

  get search() {
    return this.url.search;
  }
  set search(v) {
    const newUrl = new URL(this.url);
    newUrl.search = v;
    this.assign(newUrl);
  }

  get hash() {
    return this.url.hash;
  }
  set hash(v) {
    const newUrl = new URL(this.url);
    newUrl.hash = v;
    this.assign(newUrl);
  }

  assign(newUrl: string | URL) {
    window.history.pushState(null, 'origin:location', newUrl);
    this.reload();
  }

  replace(newUrl: string | URL) {
    window.history.replaceState(null, 'origin:location', newUrl);
    this.reload();
  }

  // eslint-disable-next-line class-methods-use-this
  reload() {
    // Do nothing
  }
}

const originalLocation = window.location;

export function mockWindowLocation(url: string) {
  //window.location = new WindowLocationMock(url);
  //document.location = window.location;
  Object.defineProperty(window, 'location', {
    writable: true,
    value: new WindowLocationMock(url)
  });
}

export function restoreWindowLocation() {
  //window.location = originalLocation;
  Object.defineProperty(window, 'location', {
    writable: true,
    value: originalLocation
  });
}

function verifyOrigin(newURL: string | URL, method: 'pushState' | 'replaceState') {
  const currentOrigin = new URL(window.location.href).origin;
  if (new URL(newURL, currentOrigin).origin !== currentOrigin) {
    // Same error message as Chrome 118
    throw new DOMException(
      `Failed to execute '${method}' on 'History': A history state object with URL '${newURL.toString()}' cannot be created in a document with origin '${currentOrigin}' and URL '${
        window.location.href
      }'.`
    );
  }
}

export class WindowHistoryMock implements History {
  private index = 0;
  // Should be private but making it public makes it really easy to verify everything is OK in some tests
  public sessionHistory: [{ state: any; url: string }] = [
    { state: null, url: window.location.href }
  ];

  get length() {
    return this.sessionHistory.length;
  }

  scrollRestoration = 'auto' as const;

  get state() {
    // eslint-disable-next-line @typescript-eslint/no-unsafe-return
    return this.sessionHistory[this.index].state;
  }

  back() {
    this.go(-1);
  }

  forward() {
    this.go(+1);
  }

  go(delta = 0) {
    if (delta === 0) {
      window.location.reload();
    }
    const newIndex = this.index + delta;
    if (newIndex < 0 || newIndex >= this.length) {
      // Do nothing
    } else if (newIndex === this.index) {
      // Do nothing
    } else {
      this.index = newIndex;

      (window.location as WindowLocationMock).internalSetURLFromHistory(
        this.sessionHistory[this.index].url
      );

      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
      dispatchEvent(new PopStateEvent('popstate', { state: this.state }));
    }
  }

  pushState(data: any, unused: string, url?: string | URL | null) {
    if (url) {
      if (unused !== 'origin:location') verifyOrigin(url, 'pushState');
      (window.location as WindowLocationMock).internalSetURLFromHistory(url);
    }
    this.sessionHistory.push({
      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
      state: structuredClone(data),
      url: window.location.href
    });
    this.index++;
  }

  replaceState(data: any, unused: string, url?: string | URL | null) {
    if (url) {
      if (unused !== 'origin:location') verifyOrigin(url, 'replaceState');
      (window.location as WindowLocationMock).internalSetURLFromHistory(url);
    }
    this.sessionHistory[this.index] = {
      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
      state: structuredClone(data),
      url: window.location.href
    };
  }
}

const originalHistory = window.history;

export function mockWindowHistory() {
  //window.history = new WindowHistoryMock();
  Object.defineProperty(window, 'history', {
    writable: true,
    value: new WindowHistoryMock()
  });
}

export function restoreWindowHistory() {
  //window.history = originalHistory;
  Object.defineProperty(window, 'history', {
    writable: true,
    value: originalHistory
  });
}
-1

Can rewrite window.location by delete this global in every test.

delete global.window.location;
const href = 'http://localhost:3000';
global.window.location = { href };
1
  • Why deleting? Why just reassignment doesn't work?
    – karlosos
    Mar 3 at 13:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.