Learning to use jest for unit test: Creating a npm command line Utility — Part 3
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.
lets see how to test CJS project:
npm install jest --save-dev
add below property to package.json
"test": "npx jest --inject-globals false"
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.
Now create a Folder named __test__ under root directory (where package.json is present)