How to test behavior in the link function of a directive

Basically, rather than test the link function itself, you’d test the outcome(s) of the directive programmatically. What you would do is write out the directive to a string, and use $compile to have angular process it. Then you test the output to make sure everything is wired up correctly.

Angular’s source is full of good examples of how to do this… for example Angular’s test of the ngRepeat directive

You can see what they’re doing is setting up the directive, Changing the scope (in this case $rootScope) making sure it’s $digested, and then testing the DOM it outputs to make sure everything is wired up correctly. You can also test what’s in the scope, if the directive is altering that.

The test for ngClick is also pretty interesting, because it shows testing of a browser interaction and it’s effect on the scope.

For sake of completeness, here’s a snippet from the ngClick tests that I think sums up testing a directive fairly well:

 it('should get called on a click', inject(function($rootScope, $compile) {
   element = $compile('<div ng-click="clicked = true"></div>')($rootScope);
   $rootScope.$digest();
   expect($rootScope.clicked).toBeFalsy();

   browserTrigger(element, 'click');
   expect($rootScope.clicked).toEqual(true);
 }));

So in the case of your scope.doStuff function, I wouldn’t test what it’s doing, so much as I’d test whatever it’s affected on the scope, and it’s subsequently effected DOM elements.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)