Adding 0% coverage in Istanbul code coverage report
In this post I am setting up a NodeJS project, it has a test project to run automation tests, i also takes care of code coverage as well. The project uses following frameworks:
- NodeJS (https://github.com/nodejs)
- Istanbul middleware (https://github.com/gotwarlost/istanbul-middleware)
- ExpressJS (https://expressjs.com/)
- Protractor (https://github.com/angular/protractor)
In first step I am creating a NodeJS project:
- Install NodeJs
- Go to project folder for example C:\\
\ - Open command prompt/terminal in the above location, run the following commands:
npm init
npm install express
- After the above commands running successfully, create a file named server.js, and have the following code:
- In the same folder create a sub-folder named public, so in the above project we are creating a static server to serve static files like html and images. In the public folder create a HTML file named index.html. Following are the contents of index.html:
- In the above public folder you may create a folder named src, under src folder you may have multiple sub-folders, each sub-folder may act as module, and each module may have single or multiple javascript files.
- Before running any testcase to test the above project all the code in src folder need to be instrumented.
- For instrumentation istanbul-instrumentor cli utility can be used. Keep the instrumented code in public-coverage folder.
- If you notice the above index.html one of the instrumented Javascript file is used, so when any automation test case launch this html file the coverage for the particular file will be collected, however other instrumented Javascript file's coverage won't be collected. However those non-loaded file's coverage should be actually 0%.
Let's create the test project which will run autonomous tests on the above project, basically it will load the index.html in browser, it will collect the coverage data and pushes it to istanbul coverage collector.
- Here Protractor is used to run autonomous tests, following is my Protractor configuration file:
- Below is the content of spec.js file:
- Now create the middle-ware NodeJS project which will run the Istanbul middle-ware(https://github.com/gotwarlost/istanbul-middleware) to handle get/post request for all coverage related data.
- Following is the middle-ware server code:
- In the above code for staticdir's value you have to give the path where your instrumented code resides.
- In node_modules/archiver/lib/core.js you have to modify the code to do coverage calculation for non-loaded files during tests. Following is the file's modified code.
- As we have modified the core .js file the node_modules/istanbul-middleware/lib/handlers.js code has to be modified. Following is the code for handler.js
- That's all. Now if you run your tests, whichever files not loaded during test will also be covered in the coverage report having 0% coverage for those.