how to test $window.open using jasmine

夙愿已清 提交于 2019-12-05 03:34:19

First of all your expectation (window.open).toHaveBeenCalled() is in wrong place. You cannot expect before spying the event. Now coming to your question there are different methods in jasmine to spy on dependencies,like

  • .and.callThrough - By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation.
  • .and.callFake - By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function.
  • .and.returnValue - By chaining the spy with and.returnValue, all calls to the function will return a specific value.

Please check Jamine doc for complete list

Sample test case for 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" );
    } ) );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!