0

I'm currently tests for an angular app I'm working on and im running into difficultly testing a function which will simply open up a new window to an external site. When I run tests on my function, I get an error

Error: Not implemented: window.open

Below is some code, the first line is where I'm getting the error

const blankWindow = window.open('', _blank);
blankWindow.location.href = externalSiteUrl

How do I fix this function to ensure I don't get this error? Is there another way to test opening a window in a new location to avoid this issue althogether?

Thanks

1 Answers1

2

You should spy on the window.open in your test.

 const windowOpenSpy = spyOn(window, 'open');

and you can verify if it was called from your method or by your actions:

expect(windowOpenSpy).toHaveBeenCalledWith(externalSiteUrl);

Update: If you want to test that open has been run then you would do:

spyOn(window, 'open').and.callThrough()

...

expect(window.open).toHaveBeenCalled()

The .and.callThrough() is really important. If you don't use it then the normal open will be replaced with a dummy/mock function which does nothing.

nircraft
  • 8,242
  • 5
  • 30
  • 46
  • Thanks for the answer. One other problem this is arising is now, when I run the function which calls the above two lines (from my question), I'm getting an error, cannot read location of undefined. Do you have any idea why this might be? –  Dec 29 '18 at 13:42
  • That is because you are trying to set the `href` `blankWindow.location.href` – nircraft Dec 29 '18 at 13:54