vue.js - 如何用 Jest + Vuejs 模拟 window.location.href?

标签 vue.js unit-testing jestjs jasmine vue-test-utils

目前,我正在为我的项目实现单元测试,并且有一个包含 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>)

我尝试了一些解决方案,但没有解决。我需要一些提示来帮助我摆脱这个麻烦。请帮忙。

最佳答案

你可以试试:

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

看看这个问题的 Jest Issue:
Jest Issue

关于vue.js - 如何用 Jest + Vuejs 模拟 window.location.href?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54021037/

相关文章:

vue.js - 类似于 VueJs 的 Angular ng-init

javascript - 如何延迟 'not found' 错误直到数据加载到 Vue.js

python - Django unittest 只读测试数据库

javascript - 开 Jest : Mock one function in a class

java - 使用 JUnit 在多线程环境中测试方法行为?

javascript - 如何比较 Jest 中的 ENOENT 错误?

javascript - 在单行而不是列中显示 Vuetify 卡?

html - 如何在 y 轴上将左右列内容相互对齐?

Angular Testing : mock a HttpResponse containing a blob

angular - 无法绑定(bind)到 'matMenuTriggerFor',因为它不是 'button' 的已知属性