Typescript coverage with Mocha & NYC
Typescript provides strict typing, empowering teams to build enterprise applications that scale. Whilst precompilers offer benefits to Javascript, they present interoperability challenges when performing coverage checks on precompiled code.
Typescript coverage reports
Coverage reports give insight into statements, functions, branches, and lines, but not necessarily quality. It stands to reason that if your application code is written in Typescript, then your tests should be too. Further to this, having coverage represented in Typescript as opposed to compiled Javascript is invaluable in the development workflow.
Typescript coverage example
This example project demonstrates how to generate a Typescript coverage report for unit tests written in Mocha and executed with NYC.
git clone git@github.com:philipbeel/example-typescript-nyc-mocha-coverage.git
The example project implements a boilerplate Typescript app for a crude calculator, with addition and subtraction files located in calculator/ts/src
. The coverage report is executed from package.json
:
cd example-typescript-nyc-mocha-coverage
npm install
npm run coverage
Coverage interoperability explained:
The command executes the following behaviour in order to generate the report:
- The
package.json
specifies configuration options for NYC, the app.ts
files are included and all test files, denoted by*.test.ts
are excluded from the coverage report - The
/test
directory includes amocha.opts
file, this tell Mocha where to find the tests that need executing. - The unit tests are run, then the results are collected by NYC, which produces a coverage summary and a generated
/coverage
directory outlining the full detailed report.
==== Coverage summary =======
Statements : 100% ( 10/10 )
Branches : 100% ( 0/0 )
Functions : 100% ( 6/6 )
Lines : 100% ( 10/10 )
==============================
Further reading:
Typescript solves a very specific problem, however, it may not be right for every situation. If you are interested in learning more here are some resources: