Search code examples
angularunit-testingjasmine

Angular unit test window.open can not find document


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

Solution

  • 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.