Integrate Istanbul for test coverage with Mocha

Even if you started programming for a short period of time or you are an experienced developer, for sure you heard about automatic tests. Why are tests useful, why are they not, is a waste of time or not is not the subject of this post.

In this article, I share with you a simple configuration that can be achieved in less than 5 minutes. It will make your project rock. Having coverage of code offers you a better understanding of where the code is not good enough tested, so in that area, the code has bigger chances to crash.

Istanbul for test coverage is one of the best tools for Node.js. In the example below I integrated Istanbul with Mocha. The configuration in package.json can be shown below.


  "scripts": {
    "test": "NODE_ENV=test mocha --require @babel/register --recursive --exit",
    "coverage": "nyc npm run test"

I have a script that runs tests using the Mocha framework. Because I use Babel, I need to require the plugin in the script. Line 6 is the only thing that you should add to run the coverage over your tests.


  "all": true,
  "include": [
  "requires": [
  "exclude": [

The file .nycrc.json contains all the configurations required. If you prefer a different file you can see all supported formats on this link. It will be loaded by default once the nyc command is fired in execution. The property required as I described before, is used because I use Babel in my project. I wanted to include only the content of src folder. I excluded some files or folders which I don’t want to be covered.

Having all these on the table now you know how to integrate Istanbul for test coverage with Mocha in your project and take advantage of the power provided by tests. If at any moment you have something unclear in your tests and you want to debug, I created an article VSCODE DEBUGGER CONFIG WITH MOCHA AND BABEL 7 where I teach you how to do it. Thank you for reading this and don’t forget to leave me a comment and subscribe to my newsletter.

Leave a Reply

Your email address will not be published.

%d bloggers like this: