Chapter 8
Writing unit tests for directives
Directives have low level access to the DOM and can be complex. This makes them
prone to errors and hard to debug. Therefore, more than the other areas of your
application, it is important that directives have a comprehensive range of tests.
Writing unit tests for directives can seem daunting at first but AngularJS provides
some nice features to make it as painless as possible and you will reap the benefits
when your directives are reliable and maintainable.
AngularJS has a comprehensive set of tests for its built-in directives.
They can be found in the test/ng/directive folder of the AngularJS
project (https://github.com/angular/angular.js/tree/
master/test/ng/directive/).
The general strategy when testing directives is as follows:
- Load the module containing the directive
- Compile a string of mark-up containing the directive to get linking function
- Run the linking function to link it to the $rootScope
- Check that the element has the properties that you expect
Here is a common skeleton unit test for a directive:
describe('myDir directive', function () {
var element, scope;
beforeEach(module('myDirModule'));
beforeEach(inject(function ($compile, $rootScope) {
var linkingFn = $compile('<my-dir></my-dir>');
scope = $rootScope;
element = linkingFn(scope);
}));
it('has some properties', function() {
expect(element.someMethod()).toBe(XXX);
});
it('does something to the scope', function() {
expect(scope.someField).toBe(XXX);
});
...
});