How to test $ window.open using jasmine

This is my function

$scope.buildForm = function (majorObjectId, name) { $window.open("/FormBuilder/Index#/" + $scope.currentAppId + "/form/" + majorObjectId + "/" + name); }; 

This is my jasmine test specification.

  it('should open new window for buildForm and with expected id', function () { scope.majorObjectId = mockObjectId; scope.currentAppId = mockApplicationId; var name = "DepartmentMajor"; scope.buildForm(mockObjectId, name); scope.$digest(); expect(window.open).toHaveBeenCalled(); spyOn(window, 'open'); spyOn(window, 'open').and.returnValue("/FormBuilder/Index#/" + scope.currentAppId + "/form/" + scope.majorObjectId + "/" + name); }); 

but when I try to run this, it opens a new tab, and I don’t want this to happen, I just want to check if returnValues ​​are present!

+8
angularjs karma-runner jasmine
source share
1 answer

First of all, your wait (window.open) .toHaveBeenCalled () is in the wrong place. You cannot wait before spying on an event. Now for your question in jasmine, there are different methods to spy on addictions, for example

  • .and.callThrough - By linking the spy to and.callThrough, the spy will still track all calls, but in addition, he will delegate the actual implementation.
  • .and.callFake . By linking the spy to and.callFake, all spy calls will delegate the provided function.
  • .and.returnValue . By associating a spy with the and.returnValue parameter, all function calls return a specific value.

Please check Jamine doc for a complete list.

Test case example below as per your requirement

 $scope.buildForm = function() { $window.open( "http://www.google.com" ); }; 

Will be

 it( 'should test window open event', inject( function( $window ) { spyOn( $window, 'open' ).and.callFake( function() { return true; } ); scope.buildForm(); expect( $window.open ).toHaveBeenCalled(); expect( $window.open ).toHaveBeenCalledWith( "http://www.google.com" ); } ) ); 
+13
source share

All Articles