为 Jest 的每个测试文件指定 window.location [英] Specify window.location for each test file for Jest
问题描述
我正在升级到 Jest 22,但在模拟 window.location
时遇到了一些问题.以前这个方法很好用,升级后就不行了.
Object.defineProperty(window.location, 'href', {可写:真实,值:'https://example.com/abc',});
我已经阅读了 Jest 文档,有一种方法可以将 package.json
中的 window.location
模拟为这样的配置.
玩笑":{"testURL": "https://example.com/home"}
这在所有测试都使用相同 URL 的情况下工作正常.
有什么办法可以在测试文件中模拟 window.location.href
.
我正在使用
"@types/jest": "^22.2.3","开玩笑": "^22.4.3","@types/enzyme": "^3.1.10","酶": "^3.3.0",
更新
这是我的组件中 window.location
的用法
const currentPage = window.location.href.match(/([^/]*)/*$/)[1];
删除 global.window.location;global.window = Object.create(window);global.window.location = {端口:'123',协议:'http:',主机名:'本地主机',}
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];
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', }
这篇关于为 Jest 的每个测试文件指定 window.location的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!