Event Callback Code Coverage

I use Karma (currently v0.10.10) and Jasmine for my unit tests and Istanbul (via karma coverage) for code coverage reports. I noticed the weird behavior of the code coverage reporter in a particular case.

The code I'm trying to check is something like this:

/** * @param {HTMLInputElement} element */ var foo = function(element) { var callback = function() { // some code }; element.addEventListener("input", callback); }; 

In my test, I send a custom input event to the element being tested and performs a callback function . The test checks the consequences of the callback and passes the test. In fact, even when I put the hairy console.log("foo") in the callback, I can clearly see that it is being printed. However , the Istanbul report erroneously indicates that the callback was not performed at all .

Changing the test code to use an anonymous function in the event listener callback eliminates the wrong behavior:

 element.addEventListener("input", function() { callback(); }); 

However, I completely despise the β€œsolutions” that modify the application code to compensate for the lack of a code quality control tool.

Is there a way in which you can get the correct code coverage without wrapping the callback with an anonymous function?

+8
javascript callback code-coverage karma-runner istanbul
source share
2 answers

The callback is passed to your method. Istanbul does not completely know where this callback came from, except from defining your function. Istanbul knows that callback () came from the callback parameter, but does not know the inside of this callback (for example, before it was passed as a callback).

// edit the example

 var callback = function(args) { //do stuff } var foo = function (callback) { // do stuff callback(arguments); } 

Now create a test for foo functionality and a separate unit test functionality for callback . A unit test should only check one thing. Each function should have its own unit test. Check that foo does what it should (regardless of the callback), and that callback does what it should (passing in your own mock data for the test). In general, these functions are always the way out.

0
source share

I had this exact problem with callbacks in some parts of my nodejs code that were not marked as private, although I had tests that definitely covered them. I had this problem with both moka / istanbul and mocha / blanket.js.

In the end, I noticed that many of my tests did not run with code spans that lead me to this problem.

I solved this by adding the --recursive to mocha, as some tests were in subdirectories.

0
source share

All Articles