9

I am upgrading to Jest 22 and I got some problem about mocking window.location. In past, this method is work fine but not work after upgraded.

Object.defineProperty(window.location, 'href', {
    writable: true,
    value: 'https://example.com/abc',
});

I have read over Jest documentation, there is a way to mock window.location in package.json as a config like this.

"jest": {
    "testURL": "https://example.com/home"
}

This is work fine in case all tests use the same URL.

Is there any way I can mock window.location.href inside the test file.

I'm using

"@types/jest": "^22.2.3",
"jest": "^22.4.3",
"@types/enzyme": "^3.1.10",
"enzyme": "^3.3.0",

Update

Here is usage of window.location inside my components

const currentPage = window.location.href.match(/([^\/]*)\/*$/)[1];
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
Natsathorn
  • 1,530
  • 1
  • 12
  • 26

2 Answers2

13

Solution from jest collaborator for June 2019:

delete global.window.location;
global.window = Object.create(window);
global.window.location = {
  port: '123',
  protocol: 'http:',
  hostname: 'localhost',
}
serv-inc
  • 35,772
  • 9
  • 166
  • 188
  • 3
    Cannot edit but don't forget after deleting the global.window.location to add it back after each test, like const { location } = window; afterEach(() => { window.location = location; }); – Mac_W Apr 24 '20 at 14:21
0

There is no really nice way at the moment. As we use react-router I dent to use it for all url changes and mock it in the tests. If you don't use react-router just create a location module like this:

export default (location) => window.location = location 

that can be easily mocked in the test

Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297