在设置或赋值“window.location”时出现Jest错误

9
我将Jest库升级到v25,所有检查位置更改的单元测试都失败了。
我查看了在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 asUnforgeable

为了修复失败的测试,我使用了以下方法:

  1. window.history.pushState({}, "title", "/testJest");

  2. 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); });


1
你的第二点正是我需要修复我的测试所需的。谢谢。 - JCE
pushState 对我解决了这个问题。 - Jonathan Chaplin
3个回答

4
只需在测试文件中添加以下代码。
  Object.defineProperty(window, 'location', {
    writable: true,
    value: { assign: jest.fn() }
  });

需要解释一下。例如,什么是想法/要点?来自帮助中心:“始终解释为什么您提出的解决方案是合适的以及它如何工作”。请通过编辑(更改)您的答案进行回复,而不是在此处进行评论(不包括“编辑:”,“更新:”或类似内容-答案应该看起来像今天写的)。 - Peter Mortensen

2

2
我不明白为什么这个答案被接受了,因为我使用 global 仍然得到相同的错误 :/ - Luckylooke

1
以下方法对我有用:

    window.history.replaceState({}, "", decodeURIComponent(url));

愉快编码 :)


这与window.location有什么关联吗?你确定这不是偶然的吗?你能详细说明一下吗? - Peter Mortensen
它会自动更改window.location,您可以在控制台中尝试一下...我复制并粘贴了此URL,并在片段中的url变量之外添加了q参数 window.history.replaceState({}, "", decodeURIComponent('https://dev59.com/abjoa4cB1Zd3GeqPG-tf#72365703?noredirect=1#comment129349849_72365703?q=dasdasdas')); voila,无需刷新即可正常工作 :) - Luckylooke
为了双重检查,甚至可以在控制台中调用 window.location + '',以查看它是否返回更改后的 window.location url ;) - Luckylooke

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