最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Specify window.location for each test file for Jest - Stack Overflow

programmeradmin8浏览0评论

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

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

"jest": {
    "testURL": ""
}

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 ponents

const currentPage = window.location.href.match(/([^\/]*)\/*$/)[1];

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./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./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 ponents

const currentPage = window.location.href.match(/([^\/]*)\/*$/)[1];
Share Improve this question edited Oct 11, 2018 at 8:19 Andreas Köberle 111k58 gold badges280 silver badges307 bronze badges asked Apr 23, 2018 at 7:54 NatsathornNatsathorn 1,5281 gold badge13 silver badges27 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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',
}

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

发布评论

评论列表(0)

  1. 暂无评论