Learning to use jest for unit test: Creating a npm command line Utility — Part 3

Praveen David Mathew
7 min readFeb 18, 2022



This is continuation of “How to create a npm commandline utility” we have already setup our utility that takes in user input using inquirer or yargs and displays “Hello User!”

Please have the setup ready, now we will see how to test this using Jest

We will see how to write jest test using typescript and non typescript, and also how to test cjs and typescript project using jest.

The final Implementation is available at : https://github.com/praveendvd/Jest_tutorial

Continure reading to understand how we did it.

Getting started:

lets see how to test CJS project:

Installing jest:

npm install jest --save-dev

Update package.json:

add below property to package.json

"scripts": {
"test": "npx jest --inject-globals false"
"jest": {
"coverageThreshold": {
"global": {
"branches": 100,
"functions": 100,
"lines": 100,
"statements": 0
"rootDir": "./",
"verbose": true,
"maxWorkers": 1,
"collectCoverageFrom": [

The script property says, when ever we call npm run test, run the specified command. Here we are preventing injecting jest globals inorder to explicitly import jest globals in the test files, as it will give autocompletion feature in vscode. You can remove — inject-globals false if you dont want to explicitly import jest globals

the jest property in package.json is to sepcify jest related configuration , here we are saying collect code coverage from all js files under root directory and the coverage should be 100% and all lines should be coverd ( statements: 0, means no statement should be missed, if we give -2 it means its ok to miss max 2 statements and so on) . You can also create a jest.config.js file instead of specifying the jest propery in package.json. We will see this in coming sections.

Writing tests:

Now create a Folder named __test__ under root directory (where package.json is present)



Praveen David Mathew

An open source advocator/WebdriverIO Projectcommiter/Postman Supernova/Postman-html-extra contributor/Stack overflow sqa moderator/Speaker