【发布时间】:2019-05-29 23:14:57
【问题描述】:
目前,我正在为我的项目实施单元测试,并且有一个包含 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>)
我尝试了一些解决方案,但没有解决。我需要一些提示来帮助我摆脱这个麻烦。请帮忙。
【问题讨论】:
-
这个问题已经在另一个帖子Here is the link to the answer得到了回答
-
不完全是你要找的东西,但
window.location.assign(url)在功能上做了同样的事情,所以你可以模拟它而不是使用jest.spyOn(window.location, 'assign').mockImplementation(() => {});
标签: vue.js unit-testing jestjs jasmine vue-test-utils