Typescript + Webpack + Code Coverage

Hi! We all know that the world of js tooling is difficult, so if you’re using Typescript, Webpack and you want to measure your tests’ code coverage (as you should), then hopefully I can give you a hand to set it up.

There’re 2 steps for this,

  • first you need to instrument your code,
  • then configure the reporter.

Using the ‘istanbul-instrumenter-loader’ for code instrumentation

With istanbul-instrumenter-loader you will instrument your sources so that after you run your tests (with that instrumentation) you can generate a report to see the code coverage.

const path = require("path");

module.exports = {
    // ...
    module: {
        rules: [
            // ...
            {
                test: /\.ts$/,
                enforce: 'post', // needed if you're using Babel
                include: path.resolve(`src/`), // instrument only sources with Istanbul
                exclude: [/node_modules/],
                loader: 'istanbul-instrumenter-loader',
                options: {
                    esModules: true // needed if you're using Babel
                }
            }
        ]
    },
    // ...
};

Using nyc for Report Generation

With nyc you will be able to

  • generate a code coverage report
  • with different formats
  • check for a pre set level of lines/functions/branches/statements’ coverage (good to enforce coverage in your project)

Define your .nycrc file where you will define your report configuration:

{
  "check-coverage": true,
  "lines": 100,
  "functions": 100,
  "branches": 100,
  "statements": 100,
  "include": [
    "src/main/**/*"
  ],
  "exclude": [
    "build/",
    "src/test/**/*"
  ],
  "reporter": [
    "lcov",
    "text"
  ],
  "extension": [
    ".ts"
  ],
  "cache": true,
  "all": true, // not only files used by tests, but all instrumented files
  "sourceMap": false, // if using babel
  "instrument": false  // if using babel
}

There are many other options in nyc that I haven’t shown but that are useful, like:

How you run this

These are the npm scripts I use to run these (I use mocha-webpack to run my mocha tests):

//...
"scripts": {
  //...
  "test:coverage": "mocha-webpack --webpack-config webpack.config.coverage.js \"src/test/**/*.ts\"",
  "coverage": "cross-env NODE_ENV=coverage nyc yarn test:coverage",
}
//...

That’s it.

Push for tests and enforce coverage!

Cheers!

Blog Logo

Tomas Alabes

Software Engineer, author, blogger and obsessive learner, from Argentina living in Silicon Valley


Published

Image

Tomas Alabes' Blog

My personal site's blog

Back to Overview