Angular单元测试窗口。打开找不到文档
在我的代码库中,我正在调用窗口。然后在调用document.write函数之后,如下所示。
public launch() {
const previewWindow = window.open('');
previewWindow.document.write(
`<iframe width="100%" height="100%" src="${this.src}"></iframe>`
);
previewWindow.document.body.setAttribute(
'style',
'padding: 0; margin: 0; overflow: hidden;'
);
}
但是,当我实施单位测试文档时,给出以下错误,
TypeError: Cannot read properties of undefined (reading 'document')
我的单位测试实现如下
it('should open url', () => {
const windowSpy = spyOn(window, 'open');
component.launch();
expect(windowSpy).toHaveBeenCalled();
});
In my codebase I am calling window.open and then after calling document.write function as follows.
public launch() {
const previewWindow = window.open('');
previewWindow.document.write(
`<iframe width="100%" height="100%" src="${this.src}"></iframe>`
);
previewWindow.document.body.setAttribute(
'style',
'padding: 0; margin: 0; overflow: hidden;'
);
}
But when I implement unit test document giving following error
TypeError: Cannot read properties of undefined (reading 'document')
My unit test implementation as follows
it('should open url', () => {
const windowSpy = spyOn(window, 'open');
component.launch();
expect(windowSpy).toHaveBeenCalled();
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的间谍不会返回任何东西。当此代码运行时:
previewwindow
仍然是零的,这就是为什么您会遇到错误的原因。在测试中执行这样的操作:
这样,当方法运行时,您将不会有未定义的值。
Your spy does not return anything. When this code runs:
previewWindow
will still be null, and that is why you're getting the error.In the test do something like this:
This way you won't have an undefined value when the method runs.