Mocking Directives for Unit Tests in AngularJS
AngularJS allows us to introduce custom HTML tags with directives. More often than not, we need to have nested directives when things become more complicated. Lets say we have a directive called feedListDirective
that will show a list of recent feeds. It has the following template
<div ng-repeat=”feed in feeds”>
<feed-directive feed=”feed”></feed-directive>
</div>
Pretty straightforward, feedListDirective
loops through each feed and let feedDirective
to actually display each feed.
This kind of nested structure introduces dependency that is not clearly addressed by dependency injection in AngularJS. We don’t specify which directive a directive is depending on the way we inject a service. Then how do we mock the nested directive (feedDirective
in this case) in unit testing?
AngularJS suffix all directives that we have declared with “Directive”. That means the feedDirective
is actually named as feedDirectiveDirective
internally. So yes, we can mock feedDirective
by mocking feedDirectiveDirective
, like this
The catch here is instead of returning an object (the Directive Definition Object), you need to return an array of DDO. That is because AngularJS actually allows multiple directives to be defined with exactly the same name. That could be handy, but I have not encountered a practical use case for it yet.
By mocking lower level directives, testing higher level directives become easier. Hopefully this can be better addressed in Angular 2.0.