6

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?

2 Answers 2

9

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
    });
}));
Sign up to request clarification or add additional context in comments.

1 Comment

What if I am having new scope object inside the child controller? Can I access both Parent and Child(with new scope object) controller?
0

This code works for accessing both Parent and Child(With new scope object) Controller.

...

var childCtrl;
var parentCtrl;
var scope;

beforeEach(inject(function($rootScope, $controller) {
  scope = $rootScope.$new();
  // First - Parent
  parentCtrl = $controller('ParentCtrl', {$scope: scope});
  // Second - Child (also with new scope object)
  ChildCtrl = $controller('ChildCtrl', {$scope: scope});
}));

... 

describe("Testing Parent and Child Controller's Scope", function() {

  it('parentObj', function(){
    expect(scope.parentObj).toBeDefined();
  });

  it('childObj', function(){
    expect(scope.childObj).toBeDefined();
  });

  it('parentObj.newPropCreatedInChild', function(){
    expect(scope.parentObj.newPropCreatedInChild).toBeDefined();
  });

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.