【问题标题】:Jest error when set or assign window.location设置或分配 window.location 时的笑话错误
【发布时间】: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

修复我使用的失败测试:

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

【问题讨论】:

  • 你的观点“2”。正是我需要修复我的测试。谢谢。

标签: javascript unit-testing jestjs window location-href


【解决方案1】:

为了简短起见,“全局”在 Jest 中是“窗口”。

用途:

global.location.assign(url);

相信你可以在这里找到剩下的答案:

How to mock the JavaScript window object using Jest?

另外,关于这个问题有一个有趣的对话:

https://github.com/facebook/jest/issues/3692

希望这能解决您的问题。

【讨论】:

    【解决方案2】:

    只需在您的测试文件中添加以下代码即可。

      Object.defineProperty(window, 'location', {
        writable: true,
        value: { assign: jest.fn() }
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-17
      • 2021-06-24
      • 2023-03-24
      • 1970-01-01
      • 2011-04-08
      • 2019-10-15
      • 2020-01-22
      • 2012-09-10
      相关资源
      最近更新 更多