I’m trying to write a unit test for a controller that’s nested, but can’t figure out how to mock the same behaviour in my test.
I have 2 controllers:
function FirstController ($scope) {
$scope.childs = [{
title : 'Hello, earth!'
}];
};
function SecondController ($scope) {
$scope.child.title = $scope.child.title + $scope.$index;
};
And in my HTML:
<div data-ng-controller="FirstController">
<div data-ng-repeat="child in childs" data-ng-controller="SecondController">
{{ child.title }}
</div>
</div>
And this works as expected (http://jsfiddle.net/tcayp/1/)
The unittests:
// FirstController
it('Should have childs', function () {
scope = {};
ctrl = new FirstController(scope);
expect(scope.childs.length).toBeGreaterThan(0);
});
// SecondController
it('Should have inherited a child', function () {
scope = {};
ctrl = new SecondController(scope);
expect(scope.child.title).toEqual('Hello, earth!0');
});
In the SecondController-test I can’t figure out how to mock the inherit chain from ng-repeat.
Ideally, with unit tests we would like to tests classes (units) in isolation. Testing 2 controller in one test might be too much: a test would become more complex and more brittle.
Taking a closer look at the provided example one might notice that it is really not about testing 2 controllers but rather making sure that data are available in a parent scope. So, focusing on one controller only (
SecondController) and the inherited data one would write a test like this:Here is the full jsFiddle: http://jsfiddle.net/pkozlowski_opensource/h8xry/13/
I would really advise against testing 2 controllers together but just for the sake of answering the question, it is possible as well:
And the jsFiddle: http://jsfiddle.net/pkozlowski_opensource/4Qy6b/1/