目前,我正在为我的项目实施单元测试,其中有一个包含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.location.assign(url)
函数实际上可以达到同样的效果,因此您可以使用jest.spyOn(window.location, 'assign').mockImplementation(() => {});
进行模拟。 - Brady Dowling