Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 spec

            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 is opening a new tab and i don't want this to happen, i just want to check whether the given returnValues are present are not!!

like image 847
Syed Rasheed Avatar asked Jul 08 '15 07:07

Syed Rasheed


People also ask

What is Jasmine used for in testing?

Jasmine is a very popular JavaScript behavior-driven development (In BDD, you write tests before writing actual code) framework for unit testing JavaScript applications. It provides utilities that can be used to run automated tests for both synchronous and asynchronous code.

How do I run a single test file in Jasmine?

Running a single specBy using fit (think of it as a focused it ), Jasmine will run only that particular spec. describe('Awesome feature', function () { fit('should check whether `true` is really `true`', function () { expect(true). toBe(true); }); });


1 Answers

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" );
    } ) );
like image 130
Bhaskar Gyan Vardhan Avatar answered Sep 30 '22 05:09

Bhaskar Gyan Vardhan