1
votes

I have a nested controller as below:

<div ng-controller="ParentController">{{ data.value }}
    <div ng-controller="ChildController">{{ data.value }}</div>
</div>

 

app.controller('ParentController', function ($scope) {
        $scope.data = {
            value: "A"
        }
    });

My child controller sets the parent scope as below:

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

My Jasmine unit test is:

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

});

The test results in "Cannot read property 'value' of undefined".

How do I unit test a child controller that uses a parent scope?

2

2 Answers

2
votes

It really depends on what you want to test. If you want to assert that the child controller changes the value during its initialization then just setup the value for the test to change. You don't need to test Angular's scope hierarchy.

So, I'd suggest just to do this:

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
votes

First initialize $scope.data={};

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

});