我将Jest库升级到v25,所有检查位置更改的单元测试都失败了。
我查看了在Jest存储库上打开的一些问题(链接),但实际上我并不理解如何解决这个问题。
调用location.assign的代码会出现以下错误:
我认为Jest jsdom的window对象不应该再被视为真正的浏览器窗口,因为它不能改变位置。如何解决这个问题?
我查看了在Jest存储库上打开的一些问题(链接),但实际上我并不理解如何解决这个问题。
调用location.assign的代码会出现以下错误:
Error: Not implemented: navigation (except hash changes)
69 | // window.location.href = url;
> 70 | window.location.assign(url);
我认为Jest jsdom的window对象不应该再被视为真正的浏览器窗口,因为它不能改变位置。如何解决这个问题?
我的发现:
- 测试中的导航不起作用。所有在浏览器中工作的方法在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 as
Unforgeable
为了修复失败的测试,我使用了以下方法:
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); });