It is important to test your custom directives in AngularJS due to the complexity of encapsulating functionality within custom HTML tags, attributes, classes, or comments. Unit tests are the best way to do this because they can cover the variety of ways the custom element can be used.
For simple directives you will need to use the $compile
method to compile the object first and then the $digest()
method to fire off all watches in the scope to ensure that expressions are evaluated. Also, if you are running multiple tests, you should create the module and inject the $compile
and $rootScope
into each test using a pretest buildup method.
To illustrate this, consider the following custom directive two-plus-two
in a template:
<two-plus-two></two-plus-two>
The controller code for the directive is shown here:
var app = angular.module('myApp', []);
app.directive('twoPlusTwo', function () {
return {
restrict: 'E',
replace: true,
template: '<h1>Two Plus Two is {{ 2 + 2 }} </h1>'
};
});
To illustrate testing the controller, I needed to pick a testing framework. The following shows an example of a Jasmine test to test the functionality of the custom directive. Notice how the myApp
module, $compile
, and $rootScope
are injected into every test using beforeEach()
and that $compile
and $digest
are used to compile and render the element and evaluate the expression.
describe('Unit testing addition', function() {
var $compile;
var $rootScope;
beforeEach(module('myApp'));
beforeEach(inject(function(_$compile_, _$rootScope_){
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
it('Adds element and handles filter', function() {
var element = $compile("<two-plus-two></two-plus-two>")($rootScope);
$rootScope.$digest();
expect(element.html()).toContain("Two Plus Two is 4");
});
});