我正在测试我的控制器,它有一个父作用域变量引用。但它给出了变量未定义的错误。
订阅(控制器)
var vm = this;
var userId=$scope.$parent.vm.userId;
var simId=$scope.$parent.vm.simId;
subscriptionSpec(规范文件)
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});
}));
});
Karma Jasmine错误
TypeError: Cannot read property 'vm' of undefined
这是因为控制器声明
var userId = $ scope。$ parent.vm.userId;
此外,如果我用实际值替换$ scope。$ parent.vm.userId,那么它不会给出任何错误。
如何为此行编写测试用例?
答案 0 :(得分:2)
尝试模拟像
这样的父范围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});
}));
});
答案 1 :(得分:0)
要扩展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;
})
});