如何使用Jest + Vuejs模拟window.location.href?

单元测试

神无阳光

2020-03-12

目前,我正在为我的项目实施单元测试,并且包含一个文件window.location.href

我想对此进行测试,这是我的示例代码:

it("method A should work correctly", () => {
      const url = "http://dummy.com";
      Object.defineProperty(window.location, "href", {
        value: url,
        writable: true
      });
      const data = {
        id: "123",
        name: null
      };
      window.location.href = url;
      wrapper.vm.methodA(data);
      expect(window.location.href).toEqual(url);
    });

但是我得到这个错误:

TypeError: Cannot redefine property: href
        at Function.defineProperty (<anonymous>)

我尝试了一些解决方案,但没有解决。我需要一些提示来帮助我摆脱困境。请帮助。

第1061篇《如何使用Jest + Vuejs模拟window.location.href?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
神奇启人 2020.03.12

最好的可能是创建一个新的URL实例,以便它分析你的字符串一样location.href做,所以它更新的所有属性location一样.hash.search.protocol等。

it("method A should work correctly", () => {
  const url = "http://dummy.com/";
  Object.defineProperty(window, "location", {
    value: new URL(url)
  } );

  window.location.href = url;
  expect(window.location.href).toEqual(url);

  window.location.href += "#bar"
  expect(window.location.hash).toEqual("#bar");
});

https://repl.it/repls/VoluminousHauntingFunctions

神无阳光 2020.03.12

我已解决此问题writable: true,方法是将其添加并移至beforeEach

这是我的示例代码:

global.window = Object.create(window);
const url = "http://dummy.com";
Object.defineProperty(window, "location", {
    value: {
       href: url
    },
    writable: true
});

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android