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 2
mkdir ts_mocha_nyc_demo cd 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 2
npm install --save-dev typescript npm install --save-dev @types/node # you may also need this
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 2 3 4
exportconst divide = (a: number, b: number): number => { if (b === 0) thrownewError("The divisor cannot be 0"); return a / b; };
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: