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?
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
});
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With