2014-11-04 57 views
1

我有一个嵌套的控制器如下:AngularJS茉莉花单元测试如何注入母公司范围

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

我的茉莉花单元测试是:

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"

如何测试使用父范围的子控制器?

回答

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"); 
    }); 
}); 
+0

测试结果仍然给我一个错误在ChildController上的“无法设置属性值”未定义“。 – user3213420 2014-11-05 01:06:34

+0

不要运行摘要。 – 2014-11-05 07:18:28

0

首先初始化$ scope.data = {};

app.controller('ChildController', function ($scope) { 
$scope.data={}; 
$scope.data.value = "B"; 

});