Pregunta

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?

¿Fue útil?

Solución

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

Otros consejos

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

});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top