我升级到Jest 22,我遇到了一些关于模仿window.location
的问题。过去,这种方法工作正常但升级后无法正常工作。
Object.defineProperty(window.location, 'href', {
writable: true,
value: 'https://example.com/abc',
});
我已经阅读了Jest文档,有一种方法可以在window.location
中模拟package.json
作为这样的配置。
"jest": {
"testURL": "https://example.com/home"
}
如果所有测试都使用相同的URL,这样可以正常工作。
我有什么方法可以在测试文件中模拟window.location.href
。
我正在使用
"@types/jest": "^22.2.3",
"jest": "^22.4.3",
"@types/enzyme": "^3.1.10",
"enzyme": "^3.3.0",
更新
以下是我的组件中window.location
的用法
const currentPage = window.location.href.match(/([^\/]*)\/*$/)[1];
答案 0 :(得分:2)
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', }
答案 1 :(得分:0)
目前没有非常好的方式。当我们使用react-router时,我会将其用于所有网址更改并在测试中模拟它。如果您不使用react-router,只需创建一个location
模块,如下所示:
export default (location) => window.location = location
可以在测试中轻松模拟