To add coverage to our library, we are going to use a tool called "Istanbul," which will instrument our code so that coverage can be recorded and reported. Install as a devDependency Istanbul. Then, we'll look at our package.json.
We'll see that Istanbul has been added to our devDependencies, and we need to make some alterations to our test scripts so that Istanbul can instrument our code for coverage reporting.
We'll do our test single one here first. What we're going to change is first we need to run the Istanbul command instead of the Mocha command. We'll say, "Istanbul cover," and then, we want to exclude our index.test.js, because that's a test file. We don't want to report coverage stats on that.
We'll exclude anything that ends in .test.js. Then, we're going to actually run the underscore Mocha command. This is in our bin as underscore Mocha. This is what Istanbul needs us to run for us to get coverage using the Mocha framework.
Now, we need to pass some arguments to the Mocha command, such as the file that we want to pass. We do this by specifying this double dash. Then, everything after here will be passed down into the binary that we're using to run our test.
We're passing our source test file. To get the coverage stats, we need to change our reporter to be spec. We'll save that, and then, we'll npm run test single.
This will run our test. We'll get the output in our console the same, but in addition, we'll get this coverage summary. We have 100 percent coverage. Let's go ahead and take a look at this file that was created, as well.
There's a coverage directory. It has a coverage.json and lcov.info. It also has this LCOV report that we can open in our browser. Let's go ahead and open that. We can browse our files, our source code, and see how many times each line was hit in our test.
It looks like we hit this line three times, and that makes sense, because we call that function one time with a number. That number just happens to be three. It iterates over that function three times.
In review, you simply install Istanbul. Then you say, "Istanbul cover." You exclude your test files, so you only cover your actual source. You change the Mocha to a underscore Mocha. Then, you add the RSpec reporter as an argument to the underscore Mocha binary.
One final thing that we want to make sure that we do is we don't want to commit this coverage folder to our source code. If we look at the get status, we'll see coverage is there but it's not a tracked file.
We want to make sure that it's not ever tracked. We'll go to our get ignore, and we'll simply add coverage in here so that that directory is ignored. If we look at the get status, we see that only the change files were...