【问题标题】:Jasmine unit test for more details AngularJs directiveJasmine 单元测试以获取更多详细信息 AngularJs 指令
【发布时间】:2015-09-14 10:48:58
【问题描述】:

我在下面设置了 Jasmine 测试。我想写一个测试来检查inAppBrowser中是否打开了一个链接。

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

这可能吗?

服务和指令:

'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);
            };
        }]
    };
}]);

单元测试:

    '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);
        });
    });

});

【问题讨论】:

    标签: unit-testing angularjs-directive jasmine


    【解决方案1】:

    beforeEach:

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

    it:

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

    您不必在单元测试中预设其他组件(inAppBrowser),该规范应该对调用window.open 时发生的情况一无所知。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多