Search code examples
javascriptunit-testingcode-coveragerequirejsjs-amd

JavaScript code coverage in RequireJS / AMD modules


Short and seemingly stupid question because so simple and you'd think ubiquitous: has anyone gotten any kind of code coverage to work within a RequireJS front-end project (non NodeJS)?

Seems like a stupid question because of the prevalence of TDD approaches in the JS world and the take-over of AMD development.

I've tried a million approaches, all are lacking. My project is a Backbone project with Jasmine Unit Tests:

1) JSTD with Coverage plugin. JSTD has trouble properly loading and instrumenting AMD modules. If I run JSTD on a single js file (combined by RequireJS optimizer) then code coverage works beautifully, EXCEPT that coverage is then collected and metrics defined on the ENTIRE file. Great, that's useless because that includes 3rd party libraries, and because I can't target a single unit to help test development. Argh.

2) JSCoverage - total fail, doesn't like AMD modules.

3) Chrome specific & Firebug specific 'live' instrumenters - fail, don't like AMD modules.

Every approach I try seems to require massive amounts of custom work. So maybe I need to spin a custom solution from scratch?

How about the following approach: expand the RequireJS optimizer to instrument code and create coverage. It would be in-memory instrumentation which can be enabled with a require.config({ instrument: true }) flag. Every time require loads a module it automatically instruments it and places it in its module repository. Coverage statistics are collected in an object underneath the global require object and accessible from anywhere, say, after a Jasmine test-run.

Input?


Solution

  • Blanket.js works with Qunit using a modified RequireJS loader. We're working on Jasmine support, and will be happy to accept any feedback or suggestions.

    If your project is going into production, Blanket.js isn't for you, but if it's just a side project it might be worth seeing if it meets your needs.

    EDIT: Blanket now supports Jasmine.