Building Your Own Directives
Load the module that contains the directive into the test, then create an element
containing this directive, using the $compile and $rootScope functions. Keep a
reference of element and $scope so that it is available in all the tests later.
Depending upon the kind of tests you are writing you may want to
compile a different element in each it clause. In this case you should
keep a reference to the $compile function too.
Finally, test whether the directive performs as expected by interacting with it
through jQuery/jqLite functions and through modifying scope.
In cases where your directive is using $watch, $observe, or $q, you will need to
trigger a $digest before checking your expectations. For example:
it("updates the scope via a $watch", function() {
scope.someField = 'something';
scope.$digest();
expect(scope.someOtherField).toBe('something');
});
In the rest of this chapter we will introduce our custom directives through their
unit tests, in keeping with the concept of Test Driven Development (TDD).
Defining a directive
Each directive must be registered with a module. You call directive() on the
module passing in the canonical name of the directive and a factory function
that returns the directive definition.
angular.module('app', []).directive('myDir', function() {
return myDirectiveDefinition;
});
The factory function can be injected with services to be used by the directive.
A directive definition is an object whose fields tell the compiler what the directive
does. Some of the fields are declarative (for example, replace: true, which tells
the compiler to replace the original element with what is in the template). Some
fields are imperative (for example, link: function(...), which provides the linking
function to the compiler.