Instrumentation can be carried out by parsing the code, injecting extra syntax nodes for the probing, and then regenerating a new, instrumented-version of the code. For running Node.js application, there are two good code coverage analyzers (among many others) you might want to look at: node-cover and coveraje. For each analyzer, the instrumenting process basically modifies the syntax tree as the code is parsed by Esprima, the high-performant ECMAScript parser I am involved with. By the way, these two projects are also examples of successful migration from UglifyJS parser to Esprima.
Update: If you also need branch coverage support, consider using Istanbul.
Surprisingly, coverage tool is easy to install and to use. I give a quick example here for node-cover but the principle of operations is the same for coveraje. After you install node-cover via its package, run it against our test.js example:
x = 42; if (false) x = -1;
cover run test.js cover report html
and then open the generated
cover_report/index.html to see the color-coded coverage report. It is easy to spot which part of the code is not touched when the script was executed:
Now here comes the Inception part. Lately I’ve been using this coverage analyzer to improve the code coverage of Esprima own parsing routines (issue 221). It’s extremely helpful, often when you write some complex statement to implement a certain programming logic, there are corner cases which need to be verified thoroughly. Hundreds of Esprima unit tests catch most of the general common cases but there were few which were overlooked.
I’m happy to share with you that now Esprima parser has a full code coverage. Report of node-cover shows that the remaining non-covered blocks are either (1) workarounds for old versions of JScript of Internet Explorer, or (2) assertions which shall be valid all the time since otherwise we have a serious logic error. Thus, to best of our knowledge, the large set of the unit tests exercises every possible parser code branch in Esprima.
Esprima has a typical contribution guide designed to maximize code quality and minimize future maintenance effort. Since it’s now rather easy to carry out this coverage analysis, a new criteria “No coverage regression” has been added to the laundry list of submitting a contribution, obviously with an added section on code coverage in the testing wiki page. Of course, kudos to Itay for his node-cover tool that makes this improvement rather fun to accomplish.
Yay for coverage!