I have a controller defined in a directive and having trouble unit testing it. Is this possible without globalizing or separating the controller from the directive?? Can you add a simple example??
1 Answer
In your case you could test the elements controller by accessing controllers functions from the compiled elements scope.
The easiest way to access the scope of the element is by calling the #scope() function on the compiled angular element.
it ('should have a function X on scope', inject(function($rootScope, $compile) {
var element = $compile('<div test-directive></div>')($rootScope);
expect(element.scope().myFunction).toEqual(jasmine.any(Function));
});
Heres a simple example of the following technique used in a jsFiddle.
5 Comments
Yoti
My directive is an element, and the template is loaded from another HTML that fails to load. How does the karma config should look like?
Kirstein
One option would be loading templates using the beforeEach(module('template.html')); pattern. A wonderful example of that technique is shown at github.com/vojtajina/ng-directive-testing . Another option would be to 'mock' the template by adding it to $templateCache by its url. Then when the directive tries to load the template it would take the template from the cache.
Luke Madera
This no longer works in Angular 1.2.x - see jsfiddle.net/lukem/VL9fm/4 - any ideas for how to fix?
Luke Madera
You have to use isolateScope() instead
FlavorScape
You have to pre-pack your templates into a js file using something like ngTemplates since angular will intercept all your http traffic, including templates.