15

JS

var link = this.notificationDiv.getElementsByTagName('a')[0];

link.addEventListener('click', function (evt){
    evt.preventDefault();
    visitDestination(next);
  }, false);
}

var visitDestination = function(next){
    window.open(next)
}

Spec

  var next = "http://www.example.com"

  it( 'should test window open event', function() {

    var spyEvent = spyOnEvent('#link', 'click' ).andCallFake(visitDestination(next));;
    $('#link')[0].click();
    expect( 'click' ).toHaveBeenTriggeredOn( '#link' );
    expect( spyEvent ).toHaveBeenTriggered();

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

How to write the spec to test for when link is clicked it calls visitDestination and to ensures window.open == next? When I try to run the spec it opens the new window.

baconck
  • 386
  • 2
  • 5
  • 19

2 Answers2

30

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.

jlogan
  • 947
  • 6
  • 9
  • I have added - chai.spy.on(window, 'open') in 'beforeEach'. But still giving error 'Not implemented: window.open'. Can you please suggest solution for this? – Mangesh Daundkar Mar 01 '19 at 10:04
  • Looks like whatever browser you're running in has not defined `window.open`. You can try `var mySpy = jasmine.createSpy('name');` and then `window.open = mySpy` – jlogan Mar 04 '19 at 22:26
  • if I use this, I am getting error like `Expected spy on open to be 'link' ` – Suryaprakash Nov 25 '21 at 12:24
4

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; }
Twonky
  • 796
  • 13
  • 31
Ravi
  • 51
  • 4