How to mock a function whose parent object is of nullable type?

302 Views Asked by At

This is my method.

redirect(){
   const url = 'localhost:4100';
   this.document.defaultView?.open(url, '_blank'); 
}

Obviously open() is present in defaultView. However, when I try to mock it, I'm getting an error open is not part of this object.

const spyOpen = spyOn(document.defaultView, 'open').and.callFake(
  (url: string, target: string = '_blank'): void => {
    url;
    target;
  }
);
1

There are 1 best solutions below

6
Estus Flask On

In Jest, it can be:

jest.spyOn(document.defaultView as Required<typeof document.defaultView>, 'open')

The problem is that if document.defaultView.open is really not a function at runtime, Jest will fail to spy on it, in this case it cannot make use of spies maintained by Jest and needs to be cleaned up manually:

originalOpen = document.defaultView.open;
document.defaultView.open = jest.fn();

// in afterEach
document.defaultView.open = originalOpen;

The same can be applied to Jasmine, adjusted for difference in API.