If you are a programmer, you probably familiar with Unit Tests and Jest. Jest is a delightful JavaScript Testing Framework with a focus on simplicity and works on React, Node, Vue or any project that has JavaScript or TypeScript.
Working in a company, code coverage is compulsory for most of the projects, like in my company, every merge request needs to have >60% code coverage on new code, otherwise It won’t be merge.
So setting up Jest to show code coverage is needed, but first, let’s install the necessary dependencies:
yarn add ts-jest typescript jest jest-environment-jsdom
After all dependencies installed, we initialize the jest config file with typescript supported:
yarn ts-jest config:init
The jest.config.js
file will be created. Before we config jest, let’s look at my directory as an example TypeScript project:
And here’s the jest.config.js
:
- For the
preset
, we gonna usets-jest
- For the
testEnvironment
, we gonna usejsdom
, because some files will have DOM manipulation so this environment will help us - The
rootDir
will be"./"
, you can set the path that suits you - Then we will have to create a
coverage
folder. - We only collect coverage from TypeScript file, instead of all files ( because there will be
json
file orhtml
file that we don’t want to collect those ), as you can see I even excludeconstant.ts
file because there aren’t anything to test from that file - For
testPathIgnorePatterns
, I ignore thenode_modules
, since this config is an array, you can pass multiple paths to ignore - For the
testMatch
, I match the tested files with their name and.spec.ts
suffix
My jest.config.js
file above is just an example, you can modify it to suit your project
Enough or the configuration, let’s create a jest
script, put this into your package.json
scripts
"test:jest": "jest --passWithNoTests --updateSnapshot --coverage"
There are 3 flags, the --passWithNoTests
so the project will pass Jest if there are no tests, the --updateSnapshot
so we won’t commit our snapshot to git, the --coverage
so It will collect the coverage from the test. Then we run
yarn test:jest
After the script finished, you can see that the coverage
folder has been created. In the folder the will be enough of coverage information for your project based on your configuration. Don’t forget to put the coverage
folder to .gitignore
Last Words
Although my content is free for everyone, but if you find this article helpful, you can buy me a coffee here