【问题标题】:Specify window.location for each test file for Jest为 Jest 的每个测试文件指定 window.location
【发布时间】:2018-10-03 04:45:11
【问题描述】:

我正在升级到 Jest 22,但在模拟 window.location 时遇到了一些问题。以前这种方法可以正常使用,但是升级后就不行了。

Object.defineProperty(window.location, 'href', {
    writable: true,
    value: 'https://example.com/abc',
});

我已阅读 Jest 文档,有一种方法可以将 window.location 中的 package.json 模拟为这样的配置。

"jest": {
    "testURL": "https://example.com/home"
}

如果所有测试都使用相同的 URL,这可以正常工作。

有什么方法可以在测试文件中模拟window.location.href

我正在使用

"@types/jest": "^22.2.3",
"jest": "^22.4.3",
"@types/enzyme": "^3.1.10",
"enzyme": "^3.3.0",

更新

这是window.location 在我的组件中的用法

const currentPage = window.location.href.match(/([^\/]*)\/*$/)[1];

【问题讨论】:

    标签: javascript reactjs jestjs


    【解决方案1】:

    目前没有真正好的方法。当我们使用 react-router 时,我将它用于所有 url 更改并在测试中模拟它。如果您不使用 react-router,只需创建一个 location 模块,如下所示:

    export default (location) => window.location = location 
    

    可以在测试中轻松模拟

    【讨论】:

      【解决方案2】:

      Solution from jest collaborator for June 2019:

      delete global.window.location;
      global.window = Object.create(window);
      global.window.location = {
        port: '123',
        protocol: 'http:',
        hostname: 'localhost',
      }
      

      【讨论】:

      • 无法编辑但不要忘记删除 global.window.location 后在每次测试后将其添加回来,如 const { location } = window; afterEach(() => { window.location = location; });
      猜你喜欢
      • 2019-03-09
      • 1970-01-01
      • 2020-04-03
      • 2020-10-27
      • 2019-09-03
      • 2020-11-21
      • 2014-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多