【发布时间】:2020-05-14 04:25:23
【问题描述】:
在 v25 上升级了 Jest 库,所有检查位置更改的单元测试都失败了。
我检查了几个在 jest repo 上打开的问题,但我实际上并不明白如何解决这个问题。
调用location.assign 的代码因以下错误而中断:
Error: Not implemented: navigation (except hash changes)
69 | // window.location.href = url;
> 70 | window.location.assign(url);
我认为 Jest jsdom 窗口对象在更改位置方面不应再被视为真正的浏览器窗口。
有什么建议吗?
我将在这里添加我的发现:
- 测试中的导航不起作用。所有这些在浏览器中工作的方法都没有在 JSDom 窗口中实现:
window.location.href = "https://myapp.com"window.location.assign("https://myapp.com")window.location.replace("https://myapp.com")-
Object.defineProperty(window.location, "href", { writable: true, value: currentUrl }); window.location has been set asUnforgeable
修复我使用的失败测试:
window.history.pushState({}, "title", "/testJest");-
delete window.location; window.location = { assign: jest.fn() };it("should navigate to the new URL", () => { const myUrl = "http://some.url"; expect(window.location.assign).toHaveBeenCalledWith(myUrl); });
【问题讨论】:
-
你的观点“2”。正是我需要修复我的测试。谢谢。
标签: javascript unit-testing jestjs window location-href