Jest can be used for both backend NodeJS and frondend framework like React, Angular, Vue, NestJS, etc.
It works with projects using: Babel, TypeScript, Node, React, Angular, Vue and more!”
I will create a basic NodeJS project to demonstrate the unit test example.
Our project folder structure will be like the attached image.
Let assume you already have installed Node in your machine.
Let me create a project folder
npm init -y command needs to be run inside the project folder to create the
package.json file. Created file will be like below.
Next step is to install the
jest package in our project. So that we can write the unit test. Here, we are installing
jest as a node module and saving in the
After installing the
jest package in the project you can see the
jset package in the
package.json file in the
dependencies section as below.
Need to configure the
jset in the
package.json file. The default text should be replaced by
jest string in
scripts/test like below.
Also for full test coverage we need to pass
--coverage in that test script.
Test setup is completed. Now, we need to write business logics and tests. As above shown folder structure. I will be creating an
--test folder inside the
area folder we will be creating two files
rectangle.js and writing logics to calculate the area of geometric shape.
Let’s create a
circle.js file as below.
Let’s create a
rectangle.js file as below.
We have already created the required files and wrote the business logics. Now, it’s time to write the actual unit test to test our business logic (area of geometric shape).
We will be writing unit tests inside the
__test folder. Test folder can also have a name like
Create a file named
circle.test.js. These files will contain our actual test:
circle.test.js we will be writing one unit test.
rectangle.test.js we will be writing two unit tests.
We have covered all the business logics and unit tests. Now, It’s time to run the test.
Now we can run
npm test which will run the unit test as well as create the coverage folder where the meninist file for test coverage is available.
Here is the test coverage report. Report is available
In the article, we have learned how to set up a basic Node project, configure
jest package for unit test and test coverage. Furthermore, we have written some business logics and unit tests for those logics. Also, ran unit tests and generated test coverage reports.
GitHub repository :