Home > OS >  Angular unit test window.open can not find document
Angular unit test window.open can not find document

Time:05-02

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();
});

CodePudding user response:

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(){}
  }
}
const windowSpy = spyOn(window, 'open').and.returnValue(previewWindowMock);

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

  • Related