javascript - 设置或分配 'window.location' 时的 Jest 错误

标签 javascript unit-testing jestjs window location-href

我将 Jest 库升级到 v25,所有检查位置更改的单元测试都失败了。
我查了a couple of issues opened on the Jest repository ,但我实际上并不明白如何解决这个问题。
调用 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 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); });
  • 最佳答案

    简而言之,“全局”在 Jest 中是“窗口”。
    利用:

    global.location.assign(url);
    
    相信您可以在 How can I mock the JavaScript window object using Jest? 中找到剩下的答案。 .
    此外,在这个问题上还有一个有趣的对话:
    I found window is global in Jest from Stack Overflow, but not mentioned in documentation #3692

    关于javascript - 设置或分配 'window.location' 时的 Jest 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59954101/

    相关文章:

    javascript - 为 Node CommonJS 模块创建不可变类

    javascript - 当资源发布到根文件夹时,Animate CC HTML5 横幅不起作用

    javascript - FullCalendar:显示每个事件的总添加时间

    javascript - Firestore 安全规则 - 如何检查 FieldValue.increment 是否有效?

    javascript - 开 Jest ,期待多行

    import - vscode 智能感知导入在 jest ts 测试中不起作用

    javascript - Javascript 中的循环引用示例?

    python - 如何针对大量数据测试相同的断言

    c# - 单元测试失败说找不到 'Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight' 程序集

    unit-testing - 如何在 VueJS 中调度 Vuex Action 时进行单元测试