Pianoc
Pianoc

Reputation: 807

Jasmine unit test for more details AngularJs directive

I have a Jasmine test set up below. I would like to write a test to check that a link is opened in the inAppBrowser.

window.open(url, '_blank', 'location=yes');

Is this possible?

Service and Directive:

'use strict';

angular.module('ui.components')
.service('MoreDetailsService', function(){
    return {
        getMoreDetails: function(ean) {
            var url = 'https://test.com' + ean;
            window.open(url, '_blank', 'location=yes');
        }
    };
})

.directive('moreDetails', ['MoreDetailsService', function(moreDetailsService) {
    return {
        restrict: 'E',
        scope: {
            ean: '@'
        },
        templateUrl: 'modules/ui.components/general/views/more-details.view.html',
        controller: ['$scope', function($scope) {

            $scope.moreDetails = function() {
                return moreDetailsService.getMoreDetails($scope.ean);
            };
        }]
    };
}]);

Unit test:

    'use strict';

    describe('moreDetails', function(){

        var scope, compile, $element, control, ean;

        TestHelper.initModule('ui.components');
        beforeEach(module('modules/ui.component

s/general/views/more-details.view.html'));

    beforeEach(inject(function(_$rootScope_, _$compile_){
        scope = _$rootScope_.$new();

        scope.product = {
            ean: 'EAN'
        };

        compile = _$compile_;
    }));

    var compileElement = function(element){
        $element = angular.element('<more-details ean="{{product.ean}}" />');
        control = compile($element)(scope);
    };

    describe('getting url', function(){    
        it('should open in the InAppBrowser', function() {
            compileElement();
            scope.$digest();
            //This is where I want to test:
            //window.open(url, '_blank', 'location=yes');

            // doesn't test for anything yet
            expect(true).toBe(true);
        });
    });

});

Upvotes: 0

Views: 230

Answers (1)

Estus Flask
Estus Flask

Reputation: 223104

In beforeEach:

spyOn(window, 'open').and.stub();

And in it:

expect(window.open).toHaveBeenCalledWith('https://test.com' + 'EAN', '_blank', 'location=yes');

You don't have to presuppose the other component (inAppBrowser) in unit test, this spec should know nothing about what happens when window.open is called.

Upvotes: 1

Related Questions