How do I get code coverage for Mocha tests without modifying the source code?

I have lots of unit tests for a Node.js application written using Mocha. Now I would like to have some test coverage data for these tests.

I have seen that Mocha supports coverage reports, but requires some preprocessing using a library such as JSCoverage. Handling JSCoverage is basically not hard, but so that everything works correctly this scenario requires you modify your source code so that depending on an environment variable either the instrumented code is exported or the original one.

This is basically the step I do not like.

What I would like to have is:

  • Write my code as usual.
  • Write my tests as usual using Mocha.
  • Get code coverage for my tests WITHOUT the need to modify either the tests or the code.

Is this possible? If so, how?

Any hint for a library that enables me to do this would be great :-)

I've ran into the same aesthetic issue. Although also a bit of a hack, I'm using the following Makefile snippet:

.PHONY: coverage

coverage:
   mv lib lib-orig
   jscoverage lib-orig lib
   mocha -R html-cov > coverage.html
   mv lib lib-cov
   mv lib-orig lib

Instead of aesthetically unpleasing code, one ends up with an unaesthetically pleasing solution hidden behind a simple makefile. At least one can continue using jscoverage :)