We had known How to Write a Library for Node.js and Browser with Mocha Unit Tests. Now, we can use some tool to calculate code coverage further.

We used mocha before, so we choose jscoverage because it can support mocha. Please done your unit tests before start.

Installation

1
npm install jscoverage --save-dev

Ignored Files

If we don’t want to include some files, we can add the list to .covignore in the root of project. And write like this:

1
2
/tests/
node_modules/

Eg. we don’t want to include test files.

Run Test with Coverage

We can run this command:

1
mocha tests/node-test.js -r jscoverage

We can find that there is just an extra parameter -r jscoverage. And modify the package.json like this:

1
2
3
4
5
6
7
{

"scripts": {
"test": "mocha tests/node-test.js -r jscoverage"
}

}

Now, we can run tests by:

1
npm test
test result

We can see the coverage information now.

1
⁍ Coverage src/md5.js line[100%]  branch[100%]

Coverage Report

If we need the detail report, we can run this:

1
mocha tests/node-test.js -r jscoverage --covout=html

The report will generate in the root with name covreporter. Open index.html in the browser:
Coverage

Red part is that we miss to test.

Additional Information

jscoverage has line and branch two types of coverage. Line coverage is the lines covered ratio, and branch coverage is the condition branches covered ratio. Eg.

1
2
3
4
5
6
7
8
var n = 1;
if(n == 1) {
++n;
++n;
++n;
} else {
++n;
}

Valid lines is 5, and it go in block if. Covered lines will be 4, so line coverage is 80%. And condition branches has 2 cases. It will cover 1 case, so branch coverage will be 50%.

Further Reading

How to Write a Library for Node.js and Browser with Mocha Unit Tests
Node.js - How to Integrate Travis CI with GitHub