Suppose you have an angular+jasmine app and your controller looks something like this:
app.controller('MyController', function($scope) {
$scope.myFunc = function() {
$scope.myArray = [];
// after some operations here
myArray.push(new_obj);
}
$scope.someOtherArray = [];
}
Additionally, I have a custom directive that is triggered by every element in myArray
. Something like this:
app.directive('myDirective', function() {
return {
// directive goes here
// and some definitions
link: function(scope, element, attrs) {
scope.someOtherArray.push(other_obj)
}
}
}
and finally, in the HTML:
<div myDirective ng-repeat="obj in myArray"></div>
So, every time I add an element to myArray
, another directive element is created and $scope.someOtherArray
is modified. That works pretty well, but I found that myFunc()
and the properties of the controller are difficult to test:
controller = $controller('MyController', { $scope: mockScope });
SpyOn(mockScope, 'myFunc').and.callThrough();
// expectGET and expectPOST here.
mockScope.myFunc();
However, after running that code, there were some objects (dependent on the custom directive) that were not being updated after calling mockScope.myFunc();
(such as someOtherArray
). Apparently, I need to compile the custom directives manually:
var element = '<div myDirective ng-repeat="obj in myArray"></div>';
element = $compile(element)(mockScope);
Well, that seems a bit awkward. I was expecting that after running mockScope.myFunc()
every side effect would take place automatically. Otherwise, I need to consider every directive involved in the process and compile each of them.
Is there a better way?