为 Jest 的每个测试文件指定 window.location

Nat*_*orn 8 javascript reactjs jestjs

我正在升级到 Jest 22,但在模拟方面遇到了一些问题window.location。过去,此方法工作正常,但升级后不起作用。

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

我已阅读过玩笑文档,有嘲笑的方式window.locationpackage.json为这样的配置。

"jest": {
    "testURL": "https://example.com/home"
}
Run Code Online (Sandbox Code Playgroud)

如果所有测试都使用相同的 URL,这可以正常工作。

有什么办法可以window.location.href在测试文件中模拟。

我正在使用

"@types/jest": "^22.2.3",
"jest": "^22.4.3",
"@types/enzyme": "^3.1.10",
"enzyme": "^3.3.0",
Run Code Online (Sandbox Code Playgroud)

更新

这是window.location我的组件内部的用法

const currentPage = window.location.href.match(/([^\/]*)\/*$/)[1];
Run Code Online (Sandbox Code Playgroud)

ser*_*inc 11

来自 Jest 合作者 2019 年 6 月的解决方案

delete global.window.location;
global.window = Object.create(window);
global.window.location = {
  port: '123',
  protocol: 'http:',
  hostname: 'localhost',
}
Run Code Online (Sandbox Code Playgroud)

  • 无法编辑,但删除 global.window.location 后不要忘记在每次测试后将其添加回来,例如 const { location } = window; afterEach(() => { window.location = 位置; }); (2认同)

And*_*rle 0

目前还没有真正好的方法。当我们使用 React-router 时,我将其用于所有 url 更改并在测试中模拟它。如果您不使用react-router,只需创建一个location如下所示的模块:

export default (location) => window.location = location 
Run Code Online (Sandbox Code Playgroud)

在测试中很容易被嘲笑