There are a lot of questions here about unit test event handlers in other languages, but I haven't been able to find a good answer when it comes to JavaScript. Specifically I'm talking about a case like:
// inside a "view" class definition:
handleCheckboxClick: function() {
this.relevantData.toggleSomeValue();
return false;
}
// later on:
$('#someCheckbox').on('click', view.handleCheckboxClick);
Clearly there is logic in the event handler (this.relevantData.toggleSomeValue()
), but at the same time no other method will ever call this handler, so it's not like unit-testing it will catch some future refactoring-related bug. And in any given JavaScript codebase there are A LOT of these handlers, so it's a non-trivial amount of work to test them.
Plus, in many JS shops (certainly in ours) there are also feature-level tests being done with Selenium that would typically catch obvious UI issues (such as when an event handler breaks).
So, on the one hand I get that "unit testing of logic == good", and I don't want to shoot myself in the foot by not testing certain code if I will pay for it later. On the other hand this particular sub-set of code seems to have a high cost and low value when it comes to unit testing. Thus, my question for the SO community is, should JS developers unit test their event handling functions?
This definitely falls under a matter of opinion, but I will go ahead and give mine :)
No
In my experience it is not cost effective to test handlers like this at the unit level. I usually end up spending a great deal of time standing up fixtures and triggering artificial events; this results in passing tests, but little confidence that my view will function properly in the real world (it isn't much fun either). I find that all that time is much better spent elsewhere.
Some sort of coverage is important though, and I try to achieve that with the following approach:
This is not true for all applications or teams, but it's proved to be the most effective thing for the teams and applications i've worked on. I'm interested to hear what others think on the matter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With