为Jest的每个测试文件指定window

为Jest的每个测试文件指定window

本文介绍了为Jest的每个测试文件指定window.location的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在升级到Jest 22,并且在模拟window.location时遇到了一些问题.过去,此方法可以正常使用,但升级后无法使用.

I am upgrading to Jest 22 and I got some problem about mocking window.location. In past, this method is work fine but not work after upgraded.

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

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

I have read over Jest documentation, there is a way to mock window.location in package.json as a config like this.

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

如果所有测试都使用相同的URL,这很好.

This is work fine in case all tests use the same URL.

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

Is there any way I can mock window.location.href inside the test file.

我正在使用

"@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];

推荐答案

Jest合作者6月份的解决方案2019 :

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

这篇关于为Jest的每个测试文件指定window.location的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 04:31