设置或分配window.location时出现玩笑错误 [英] Jest error when set or assign window.location
问题描述
v25上的Jest库已升级,并且所有检查位置更改的单元测试均失败.
Upgraded Jest library on v25 and all unit tests that were checking location change are failing.
我检查了开玩笑的几个问题回购,但实际上并没有了解如何解决此问题.
I checked a couple of issues opened on jest repo but I didn't actually understood how can this be fixed.
调用location.assign
的代码因以下错误而中断:
The code that calls location.assign
breaks with following error:
Error: Not implemented: navigation (except hash changes)
69 | // window.location.href = url;
> 70 | window.location.assign(url);
我认为就更改位置而言,不再应该将Jest jsdom窗口对象视为真正的浏览器窗口.
I suppose that Jest jsdom window object shouldn't be treated anymore like a real browser window in regards to changing the location.
有什么建议吗?
我将在这里添加我的发现:
- 测试中的导航无效.在浏览器中可用的所有这些方法均未在JSm窗口中实现:
-
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
不可伪造
- Navigation in the tests doesn't work. All these methods that work in browser are not implemented in the JSDom window:
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
要修复我使用的失败测试:
To fix failing tests I used:
-
window.history.pushState({}, "title", "/testJest");
-
delete window.location; window.location = { assign: jest.fn() };
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); });
it("should navigate to the new URL", () => { const myUrl = "http://some.url"; expect(window.location.assign).toHaveBeenCalledWith(myUrl); });
推荐答案
简而言之,Jest中的"global"是"window".
To keep it short, "global" is "window" in Jest.
使用:
global.location.assign(url);
我相信您可以在此处找到其余答案:
I believe that you can find the rest of the answer here:
此外,在这个问题上,有一个有趣的话题:
Also, there is an interesting conversation around this on this issue:
https://github.com/facebook/jest/issues/3692
希望这可以解决您的问题.
Hope this solves your problem.
这篇关于设置或分配window.location时出现玩笑错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-