Background
In computer science, code coverage is a measurement of how many lines/blocks/arcs of your code are executed while the tests are running. A code coverage system collects information about the running program and then combines that with source information to generate a report on the test suite’s code coverage.
Issue
You’ve got some experience testing with Mocha, so you write a few tests and run them for your React/ES6 app, but it’s not working. Why? Because by default, Mocha only knows ES5 and you are not able to test ES6/ES7 or *.jsx.
Solution
Istanbul/NYC
Istanbul instruments your ES5 and ES2015+ JavaScript code with line counters, so that you can track how well your unit-tests exercise your codebase.
The NYC command-line-client for Istanbul works well with most testing frameworks: tap, mocha, AVA, etc.
Prerequisites:
- Nodejs is already installed. (please access https://nodejs.org/en/ to download recommended version)
- npm install Istanbul –save-dev
- npm install babel-plugin-istanbul –save-dev
- npm install cross-env –save-devs
- npm install mocha –save-dev
- npm install nyc –save-dev
Steps to set up:
For example, there is a project, and its structure is like the below screenshot:
And all of your test files are located in this test folder. For now, you can use this command “cross-env NODE_ENV=test nyc –extension .jsx –extension .es6 –reporter=lcov –reporter=text mocha \”test/**/*@(.js|.jsx)\” –require test/test_helper.js –compilers js:babel-core/register” in the scripts stanza of your package.json file.
After you execute the command “npm test”, you will get a coverage report as below:
Also, you can view the code coverage report with html under coverage/Icov-report folder.
If you click one of the file names, you’ll see detailed coverage info for this specific JavaScript file.
There are several coverage criteria, the key points are:
- Function coverage: has each function (or subroutine) in the program been called.
- Statement coverage: has each statement in the program been executed.
- Branch coverage: has each branch (also called DD-path) of each control structure (such as in if and case statements) been executed. For example, given an if statement, have both the true and false branches been executed. Another way of saying this is, has every edge in the program been executed.
- Line coverage: has each executable line in the source file been executed.
- For each case, the percentage represents executed code vs not-executed code, which equals each fraction in percent format (e.g: 50% branches, 1/2).
In the file report:
- ‘E’ stands for ‘else path not taken’, which means that for the marked if/else statement, the ‘if’ path has been tested but not the ‘else’.
- ‘I’ stands for ‘if path not taken’, which is the opposite case: the ‘if’ hasn’t been tested.
- The xN in left column is the amount of times that line has been executed.
- Not executed lines, or pieces of code, will be highlighted in red.