174

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

21 Answers 21

191

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
114

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
  • 34
    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
  • 12
    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
  • 1
    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
  • 1
    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

13

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
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");
});
4

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);
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

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
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,
  });

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.