Having recently transitioned from the good old Javascript to TypeScript, I found myself trying to shift my testing workflow to TypeScript. What I wanted to achieve, was to write my tests in TypeScript and run them without ever creating any transpiled .js file in my project. I obviously also wanted to calculate the code coverage against the TypeScript code (and not the temporarily transpiled JavaScript code) - which is done through the use of sourcemaps.

In order to realize this, I used the following tools :

  • mocha is the unit testing framework
  • istanbul is the code coverage tool that computes statement, line, function and branch coverage
  • nyc is the istanbul command line interface (replacement for the old istanbul bin)
  • ts-node is a TypeScript execution environment for node

 

Setting up the project

Assuming that you already have a TypeScript project, you will then need to install ts-node and nyc :

npm i nyc ts-node -D

 

Next, let's define the npm t and npm run cover command, instructing mocha to use ts-node to compile the .ts files.

"test": "NODE_ENV=test mocha --recursive --compilers ts:ts-node/register --bail",
"cover": "NODE_ENV=test nyc npm t",

 

We then need to configure nyc in the package.json file :

"nyc": {
  "include": [
    "app/*.ts",
    "app/**/*.ts"
  ],
  "exclude": [
    "typings"
  ],
  "extension": [
    ".ts"
  ],
  "require": [
    "ts-node/register"
  ],
  "reporter": [
    "json",
    "html"
  ],
  "all": true
}

 

That's it ! You are now all set ; you can execute npm run cover and the code coverage reports will be created in the coverage folder.

 

Difficulties encountered

Luckily for you, the workflow described above works as expected. However, when I was setting it up for the first time, I encountered multiple issues:

 

 

After all theses issues were fixed, I finally had the TypeScript testing/code coverage workflow I wanted.

 

Merging multiple coverage reports

In my project, I use two different testing frameworks: mocha for unit tests and Cucumber for functional tests.

So I ended up with a code coverage report for each one. I wanted to merge them to have a better overview on the covered code. To do so, I wrote a small script to merge multiple coverage json reports into a single html report :

 

Summary

Please, keep in mind that achieving a high code coverage absolutely does not mean that your application is bug-free. While it can be good to have some metrics about the coverage, it has no correlation with the code quality whatsoever.

If you have any comments, feel free to leave them below.