fredrik fredrik - 2 months ago 5
AngularJS Question

Unit test for nested controllers

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.

Answer

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:

describe('Testing the SecondController controller', function() {

    var $parentScope, $scope, ctrl;
    it('should prepare title', inject(function($rootScope, $controller) {

        //setup hierarchy of scopes with data             
        $rootScope.childs = [{
            title : 'Hello, earth!'
        }];
        $scope = $rootScope.$new();
        $scope.$index = 1;

        ctrl = $controller('SecondController', {
            $scope: $scope
        });

        expect($scope.childs[0].title).toEqual('Hello, earth!1');        
    }));
});

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:

describe('Testing the SecondController controller', function() {

    it('should prepare title', inject(function($rootScope, $controller) {

        $controller('FirstController', {
            $scope: $rootScope
        });

        var $scope = $rootScope.$new();
        $scope.$index = 1;

        ctrl = $controller('SecondController', {
            $scope: $scope
        });

        expect($scope.childs[0].title).toEqual('Hello, earth!1');        
    }));
});

And the jsFiddle: http://jsfiddle.net/pkozlowski_opensource/4Qy6b/1/