It’s a pleasure to work with a project that uses TypeScript for your source code and tests, although setting up test coverage can be a bit tricky. I recently started a project that uses TypeScript for source as well as the tests.

I used Mocha to run the test and nyc for generating test coverage.

It tooks many hours to figure out a solution that works end-to-end so I wanted to share the end result.

Here is what the npm script section is looking like:

  "scripts": {
    "test": "nyc --require ts-node/register ./node_modules/.bin/_mocha",
  },
  "nyc": {
    "include": [
      "src/**/*.ts",
      "src/**/*.tsx"
    ],
    "exclude": [
      "node_modules/",
      "dist/"
    ],
    "extension": [
      ".ts",
      ".tsx"
    ],
    "require": [
      "ts-node/register"
    ],
    "reporter": [
      "text-summary",
      "html"
    ],
    "sourceMap": true,
    "instrument": true
  },

Mocha configuration is located in test/mocha.opts:

--compilers ts-node/register
--full-trace
--bail
src/**/*.test.ts src/**/*.test.tsx

That’s it! Now you can run npm test to run your tests and get coverage report.

Now all test coverage reports are mapped using sourcemaps.