【问题标题】:Test statement containing parent scope variable using Karma使用 Karma 包含父范围变量的测试语句
【发布时间】:2016-01-28 08:08:34
【问题描述】:

我正在测试具有父范围变量引用的控制器。但它给出了变量未定义的错误。

订阅(控制器)

var vm = this;
var userId=$scope.$parent.vm.userId;
var simId=$scope.$parent.vm.simId;

订阅规范(规范文件)

describe('subscription controller',function (){
    var SubscriptionListCtrl,scope;
    beforeEach(module('app'));

    beforeEach(inject(function($controller,$compile,SubscriptionService,dataTableConfigService,commonUtilityService){
    scope={};
    scope.vm={};

    SubscriptionListCtrl=$controller("SubscriptionListCtrl",{$scope:scope,$compile:$compile,SubscriptionService:SubscriptionService,dataTableConfigService:dataTableConfigService,commonUtilityService:commonUtilityService});

    }));
});

业力茉莉花错误

TypeError: Cannot read property 'vm' of undefined

这是因为控制器声明

var userId=$scope.$parent.vm.userId;

另外,如果我将 $scope.$parent.vm.userId 替换为实际值,那么它不会给出任何错误。

这行的测试用例怎么写?

【问题讨论】:

    标签: angularjs unit-testing jasmine karma-jasmine


    【解决方案1】:

    尝试像模拟父作用域

    describe('subscription controller',function (){
        var SubscriptionListCtrl,scope;
        beforeEach(module('app'));
    
        beforeEach(inject(function($controller,$rootScope,$compile,SubscriptionService,dataTableConfigService,commonUtilityService){
        scope = $rootScope.$new();
        scope.$parent = {vm: {userId: 1, simId: 2}};
        scope.vm={};
    
        SubscriptionListCtrl=$controller("SubscriptionListCtrl",{$scope:scope,$compile:$compile,SubscriptionService:SubscriptionService,dataTableConfigService:dataTableConfigService,commonUtilityService:commonUtilityService});
    
        }));
    });
    

    【讨论】:

    • 它给出了同样的错误。现在我使用 $stateParams 来获取变量,而不是使用 $parent 范围变量。所以运行测试用例没有抛出任何错误。无论如何感谢您的帮助
    【解决方案2】:

    要扩展 vpsingh016 答案应该做些什么来给出想要的结果是定义父控制器和父范围,并在初始化时定义 $scope.$parent = $parentScope。例如:

    describe('Controller: TestController', function () {
    
        beforeEach(module('App'));
    
        var $controller, $scope, $parentController, $parentScope;
    
        beforeEach(inject(function (_$controller_, _$rootScope_) {
    
            $scope = _$rootScope_.$new();
            $parentScope = _$rootScope_.$new();
            $scope.$parent = $parentScope;
    
            $parentController = _$controller_('ParentController', {'$scope': $parentScope});
            $controller = _$controller_('TestController', {'$scope': $scope});
        }));
        it('should get $parent variable', function () {
            var userId=$scope.$parent.vm.userId;
            var simId=$scope.$parent.vm.simId;
        })
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-13
      • 1970-01-01
      • 2016-03-20
      • 1970-01-01
      • 1970-01-01
      • 2015-12-10
      • 1970-01-01
      • 2020-11-09
      相关资源
      最近更新 更多