4

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 1

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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?
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.
This no longer works in Angular 1.2.x - see jsfiddle.net/lukem/VL9fm/4 - any ideas for how to fix?
You have to use isolateScope() instead
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.