目前,我正在为我的项目实施单元测试,并且有一个文件包含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>)
我该如何解决呢?
你可以试试:
window = Object.create(window);
const url = "http://dummy.com";
Object.defineProperty(window, 'location', {
value: {
href: url
},
writable: true // possibility to override
});
expect(window.location.href).toEqual(url);
看看这个问题的 Jest Issue:
玩笑问题 https://github.com/facebook/jest/issues/5124
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)