Testing Typescript Project With Mocha and Istanbul NYC
Mocha is a popular JS test framework, and Istanbul is a popular JS test coverage tool. How to use them when it comes to Typescript? This post shows a simple demo.
Creating a basic TS Project
Let's create a very basic Typescript project as our demo.
First, create a directory to store this project:
1 | mkdir ts_mocha_nyc_demo |
Initialize this directory as a new npm project with the command below, which generates a package.json
file with default configuration.
1 | npm init -y |
Then, install Typescript in this npm project:
1 | npm install --save-dev typescript |
Initialize Typescript with the command below, which generates a tsconfig.json
file with default configuration.
1 | tsc --init |
Finally, write some code for testing later.
1 | mkdir src && touch src/divide.ts |
Edit src/divide.ts
:
1 | export const divide = (a: number, b: number): number => { |
Setting up Mocha and Run Test
Installing Chai and Mocha
Chai is an assertion library working well with Mocha. We often use them together.
To install Chai, Mocha, and their type definitions, run the following commands:
1 | npm install --save-dev chai @types/chai |
Writing Test Code
Create a test
directory and create a divide.test.ts
for testing divide.ts
:
1 | mkdir test && touch test/divide.test.ts |
Edit test/divide.test.ts
:
1 | import { assert, expect } from "chai"; |
Running Test
Note that mocha is natively a JS test framework, and we need to configure it before we can test TS code with it.
First, install cross-env
and tsx
:
1 | npm install --save-dev cross-env tsx |
cross-env is a useful tool for setting environment variables across platforms.
I tried ts-node just like the example provided by Mocha but I encountered an
ERR_UNKNOWN_FILE_EXTENSION
like this. Finally I use tsx and it works.
Update package.json
to be like this:
1 | { |
Now, you can run test by running the command below:
1 | npm test |
You will see output like:
1 |
|
Setting up Istanbul NYC and Run Coverage Test
Installing Istanbul NYC
To install Istanbul NYC, run:
1 | npm install --save-dev nyc @istanbuljs/nyc-config-typescript |
Configuring Istanbul NYC
Create a .nycrc.json
and edit:
1 | { |
Running Coverage Test
Update package.json
:
1 | { |
Run the coverage test with:
1 | npm run coverage |
The output may be:
1 |
|
You can also see the result in a web ui by opening ./coverage/index.html
.