Reputation: 485
When having an angular directive that inside its template has a button with ng-click attribute, should I test the effect of actual action taken (clicking) or of, an attached to ng-click attribute, function call?
In other words, for a directive, that has a template like this:
<div>
<button ng-click="game.start()">start</button>
</div>
should I test what clicking does or what game.start function does?
I am aware that later the function game.start can be changed for a different one. Also, ng-click can be removed and click event can be caught in a different way.
Unit testing with triggerHandler('click') is tempting but directive's template can also change. That would mean that I need some "proven" access to DOM nodes, namely through id attributes.
Should I attach id attributes on nodes just for unit testing sake or should I take a different aproach to the problem?
Upvotes: 3
Views: 2749
Reputation: 1756
In the case of a directive I usually go through the dom to click the element. in your case here:
it("performs some action when clicked", function() {
element.find("button").click();
assert(something);
});
Calling the handler directly will get you a passing test even if you forget to add the ng-click
directive, which is not what I usually want. It also gives you the freedom to rename the handler method without having to adjust the test, thus making it a little less brittle.
If the template is getting very complex and you are tempted to add ids just for testings sake, you might want to consider breaking the directive into multiple ones.
Upvotes: 0