我有一个嵌套控制器,如下所示:
<div ng-controller="ParentController">{{ data.value }}
<div ng-controller="ChildController">{{ data.value }}</div>
</div>
app.controller('ParentController', function ($scope) {
$scope.data = {
value: "A"
}
});
我的子控制器将父范围设置如下:
app.controller('ChildController', function ($scope) {
$scope.data.value = "B";
});
我的Jasmine单元测试是:
describe('ChildController', function () {
var scope, $rootScope;
beforeEach(inject(function ($controller, _$rootScope_) {
$rootScope = _$rootScope_;
scope = $rootScope.$new();
$controller('ChildController', { $scope: scope});
scope.$digest();
}));
it('should change parent scope', function () {
expect(scope.data.value).toEqual("B");
});
});
测试结果为"Cannot read property 'value' of undefined"
。
如何对使用父作用域的子控制器进行单元测试?
答案 0 :(得分:2)
这实际上取决于你想要测试的内容。如果要断言子控制器在初始化期间更改了值,则只需设置要更改的测试值。您不需要测试Angular的范围层次结构。
所以,我建议只是这样做:
describe('ChildController', function () {
var scope, $rootScope;
beforeEach(inject(function ($controller, _$rootScope_) {
$rootScope = _$rootScope_;
scope = $rootScope.$new();
//setup
scope.data = { value: "A" };
$controller('ChildController', { $scope: scope});
scope.$digest();
}));
it('should change parent scope', function () {
expect(scope.data.value).toEqual("B");
});
});
答案 1 :(得分:0)
首先初始化$ scope.data = {};
app.controller('ChildController', function ($scope) {
$scope.data={};
$scope.data.value = "B";
});