Jasmine.js Testing - spy on window.open

So, window.open is a method provided by the browser. I don't believe it resets the value of itself. So this:

expect(window.open).toBe('http://www.example.com');  

... is going to fail no matter what.

What you want is to create a mock of the window.open method:

spyOn(window, 'open')

This will allow you to track when it has been run. It will also prevent the actual window.open function from running. So a new window will not open when you run the test.

Next you should test that the window.open method was run:

expect(window.open).toHaveBeenCalledWith(next)

Edit: More detail. If you want to test that visitDestination has been run then you would do:

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

...

expect(window.visitDestination).toHaveBeenCalled()

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


In new version of jasmine(3.5) above solution is not working. I found some work around to fix new window open while running test cases. Add below line of code before calling your window.open(url,_blank);

 window.open = function () { return window; }