Angular单元测试窗口。打开找不到文档

发布于 2025-01-25 06:53:44 字数 749 浏览 2 评论 0原文

在我的代码库中,我正在调用窗口。然后在调用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月下凄凉 2025-02-01 06:53:44

您的间谍不会返回任何东西。当此代码运行时:

      const previewWindow = window.open(''); 
      previewWindow.document

previewwindow仍然是零的,这就是为什么您会遇到错误的原因。

在测试中执行这样的操作:

const previewWindowMock = {
  document: {
    write() { },
    body: {
      setAttribute() { }
    }
  }
} as unknown as Window;
const windowSpy = spyOn(window, 'open').and.returnValue(previewWindowMock);

这样,当方法运行时,您将不会有未定义的值。

Your spy does not return anything. When this code runs:

      const previewWindow = window.open(''); 
      previewWindow.document

previewWindow will still be null, and that is why you're getting the error.

In the test do something like this:

const previewWindowMock = {
  document: {
    write() { },
    body: {
      setAttribute() { }
    }
  }
} as unknown as Window;
const windowSpy = spyOn(window, 'open').and.returnValue(previewWindowMock);

This way you won't have an undefined value when the method runs.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文