Here’s how alert directive is tested in angular-ui/bootstrap.
Here’s another simple set of tests, for the buttons directive.
Here are a few tips:
-
Be sure to tell the test runner what module you are testing with
beforeEach(module('myModule')). -
If you have external templateUrls in your directives, you’ll want to somehow pre-cache them for the test runner. The test runner can’t asynchronously
GETtemplates. In bootstrap, we inject the templates into the javascript with a build step, and make each template a module. We usegrunt-html2jsgrunt task. -
In your tests, use the
injecthelper in abeforeEachto inject $compile and $rootScope and any other services you’ll need. Usevar myScope = $rootScope.$new()to create a fresh scope for each test. You can dovar myElement = $compile('<my-directive></my-directive>')(myScope);to create an instance of your directive, and have access to its element. -
If a directive creates its own scope and you want to test against it, you can get access to that directive’s scope by doing
var directiveScope = myElement.children().scope()– It will get the element’s child (the directive itself), and get the scope for that. -
For testing timeouts, you can use
$timeout.flush()to end all pending timeouts. -
For testing promises, remember that when you resolve a promise, it will not call its
thencallbacks until the next digest. So in tests you have to do this a lot:deferred.resolve(); scope.$apply();.
You can find tests for directives of varying complexity in the bootstrap repo. Just look in src/{directiveName}/test/.