Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify window.location for each test file for Jest

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];
like image 952
Natsathorn Avatar asked Apr 23 '18 07:04

Natsathorn


People also ask

What is the difference between window location and document location?

The window. location is read/write on all compliant browsers. The document. location is read-only in Internet Explorer but read/write in Firefox, SeaMonkey that are Gecko-based browsers.

What is window location pathname?

window.location.pathname returns the path and filename of the current page. window.location.protocol returns the web protocol used (http: or https:) window.location.assign() loads a new document.


1 Answers

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',
}
like image 166
serv-inc Avatar answered Oct 06 '22 19:10

serv-inc