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

9

我正在升级到Jest 22,但在模拟window.location时遇到了一些问题。 在过去,这种方法很有效,但在升级后就不起作用了。

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

我已经阅读了Jest文档,这里有一种方式可以在package.json中通过配置来模拟window.location

"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];
2个回答

13

3
无法编辑,但在删除 global.window.location 后,不要忘记在每个测试之后将其添加回来,例如 const { location } = window; afterEach(() => { window.location = location; }); - Mac_W

0

目前没有真正好的方法。因为我们使用了react-router,所以我倾向于在所有URL更改和测试中使用它,并在测试中模拟它。如果你不使用react-router,只需创建一个像这样的location模块:

export default (location) => window.location = location 

可以在测试中轻松模拟的


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接