AngularJS - Testing a directory link function, how to monitor a controller

If I have such a directive

JS:

app.controller('MyController', function($scope) { this.someMethod = function() { }; }); app.directive('myDirective', function() { return { scope: true link: function(scope, elem, attrs, controller) { controller.someMethod(); } controller: 'MyController', } }); 

I want to create a Jasmine spy to ensure that the link function is called controller.someMethod , but this will not work:

Spec:

 var elem = angular.element('<div my-directive></div>'); var scope = $rootScope.new(); $compile(elem)(scope); var ctrl = elem.controller('myDirective'); spyOn(ctrl, 'someFunc').andCallThrough(); 

The spy is created too late because the controller instance was created and the communication function is called in the $compile statement.

What other ways are there to track what happens in the link function? Is it possible to create an instance of the controller before hand and pass it to $compile ?

+7
angularjs unit-testing jasmine
source share
1 answer

On the AngularJS Developer Guide on Directives page:

Best practice: use a controller if you want to open the API for other directives. Otherwise use the link .

I suggest creating a service for any someMethod() . Then you can make fun and spy on this service. Otherwise, you may have to look for another sign that what you wanted really happened.

+7
source share

All Articles