I use Karma (currently v0.10.10) and Jasmine for my unit tests, and Istanbul (via karma-coverage) for code coverage reports. I've noticed a strange behaviour of the code coverage reporter in a particular case.
The code I'm trying to test is roughly this:
/**
* @param {HTMLInputElement} element
*/
var foo = function(element) {
var callback = function() {
// some code
};
element.addEventListener("input", callback);
};
In my test, I dispatch a custom input event on the tested element and the callback function executes. The test checks the effects of the callback, and the test passes. In fact, even when I put a hairy console.log("foo")
in the callback, I can clearly see it being printed out. However, Istanbul's report erroneously indicates that the callback was not executed at all.
Modifying the tested code to use an anonymous function in the event listener's callback fixes the misbehaviour:
element.addEventListener("input", function() {
callback();
});
However, I utterly despise "solutions" that modify the application's code to compensate for a code quality control tool's deficiency.
Is there a way I can make the code coverage get picked up correctly without wrapping the callback in an anonymous function?