user7816390
user7816390

Reputation:

Fixing error: not implemented: window.open during angular testing

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

Upvotes: 0

Views: 4983

Answers (1)

nircraft
nircraft

Reputation: 8478

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.

Upvotes: 2

Related Questions