Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get code coverage information using Node, Mocha

Tags:

I've recently started getting into unit testing for my Node projects with the help of Mocha. Things are going great so far and I've found that my code has improved significantly now that I'm thinking about all the angles to cover in my tests.

Now, I'd like to share my experience with the rest of my team and get them going with their own tests. Part of the information I'd like to share is how much of my code is actually covered.

Below is a sample of my application structure which I've separated into different components, or modules. In order to promote reuse I'm trying to keep all dependencies to a minimum and isolated to the component folder. This includes keeping tests isolated as well instead of the default test/ folder in the project root.

| app/ | - component/ | -- index.js | -- test/ | ---- index.js 

Currently my package.json looks like this. I'm toying around with Istanbul, but I'm in no way tied to it. I have also tried using Blanket with similar levels of success.

{   "scripts": {     "test": "clear && mocha app/ app/**/test/*.js",     "test-cov": "clear && istanbul cover npm test" } 

If I run my test-cov command as it is, I get the following error from Istanbul (which is not helpful):

No coverage information was collected, exit without writing coverage information 

So my question would be this: Given my current application structure and environment, how can I correctly report on my code coverage using Istanbul (or another tool)?


TL;DR

How can I report on my code coverage using Node, Mocha, and my current application structure?


EDIT

To be clear, Mocha is running tests correctly in this current state. Getting the code coverage report is what I'm struggling with getting to work.

EDIT 2

I received a notification that another question may have answered my question already. It only suggested installing Istanbul and running the cover command, which I have done already. Another suggestion recommends running the test commands with _mocha, which from some research I have done is to prevent Istanbul from swallowing the flags meant for Mocha and is not necessary in newer versions of Mocha.

like image 799
Chris Wright Avatar asked May 27 '15 18:05

Chris Wright


1 Answers

You should try running your test like this :

istanbul cover _mocha test/**/*.js 
like image 137
Sachacr Avatar answered Nov 03 '22 21:11

Sachacr