Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Parent Controller Scope's Variable in Angular JS With Karma and Jasmine

I have two controllers on a page. They are "wrapped" on a HTML mark-up with one being the "parent" and the other being the "child" like so:

<div id="parent" ng-controller="parentController">
    <div id="child" ng-controller=childController">
    </div>
</div>

In the JS files for my controllers, I reference an object from the "parent" controller in the "child" controller.

Parent controller:

angular.module('myApp').controller('parentController', function($scope){
    $scope.myReferencedObject = {};
    $scope.myReferencedObject.someProperty = "hello world";
});

Child controller:

angular.module('myApp').controller('childController', function($scope){
    $scope.childControllerVariable = $scope.myReferencedObject.someProperty;
});

Because the "child" controller is nested within the "parent" controller, the object from the parent controller is inherited in the child controller.

This doesn't work in a Karma test since all of the files are broken down into individual units and tested separately. The $scope.myReferencedObject.someProperty reference is undefined in my "child" controller when unit tested because there is no prototypal inheritance.

How do I solve this problem in Karma?

like image 412
Lloyd Banks Avatar asked May 01 '14 14:05

Lloyd Banks


1 Answers

You can initialize the $scope to be whatever you want when you test your inner controller so you can mock out what the parent controller would have set on it

var controllerInstance;
beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    scope.myReferencedObject = {someProperty: 'hello world'}
    controllerInstance = $controller('childController', {
      $scope: scope
    });
}));
like image 123
rob Avatar answered Sep 20 '22 03:09

rob