How To Write Unit Tests In NodeJS With JEST Test Library

A beginner’s Guide with an example project

Bhargav Bachina
Feb 9 · 7 min read

Unit testing is as important as developing a project nowadays and it becomes an integral part of development. It actually boosts the quality of the code and the confidence of developers. Sometimes you have to fix the code that is in production and you make some changes before deploying that in the production environment. Your confidence level definitely increases when you have quality unit tests written for these applications.

There are so many libraries that can be used for unit testing in nodejs applications. Jest library is one of them. According to their website, Jest is a delightful JavaScript Testing Framework with a focus on simplicity. Jest aims to work out of the box, config free, on most JavaScript projects.

Make tests that keep track of large objects with ease. Snapshots live either alongside your tests or embedded inline. Tests are parallelized by running them in their own processes to maximize performance. From it to expect - Jest has the entire toolkit in one place. Well documented, well maintained, well good.

In this post, we will see how we can get started with the Jest library with some example projects.

Prerequisites

The prerequisite for this post is the basic understanding of Javascript and how functions work. You need to have the NodeJS installed and any text editor.

You can see the below post to completely understand the functions in Javascript. You need to understand how function call works from this. There is another Test library called Tap you can use for Node Testing. Refer to the second link.

Example Project

Here is an example project you can clone on your local machine and practice. We are using the Node Tap library for unit testing.

// clone the project
git clone https://github.com/bbachi/nodejs-unit-testing-jest.git
// install dependencies and run
npm install
npm run dev
// Tetsing the library
npm test

Install Jest and Setup

First, we need to install the Jest library with the following command. Since we run unit tests mostly in the development phase, we need to use the flag --save-dev. Make sure you run this command in the root folder.

npm install jest --save-dev

Once the Jest is installed, it has the test runner executable and the location of the test runner is node_modules/.bin/jest. You can add the npm scripts section of the package.json file as below.

package.json

All you need to run the below command to run the tests.

npm test

Writing the First Test

Let’s write the first test. We have a simple Calculator file that has three functions add, subtract and multiply as below.

calculator.js

I have created a test folder and create a test file for this. We don’t have to import the jest module for testing. The jest module is made available implicitly by jest at execution time. You need to wrap all tests in the test and write all the assertions in the callback. The method expect is made available implicitly by the jest library.

calculator.test.js

Let’s run the command node test/calculator.test.jsand you will see the following output.

Tests Output

You can generate the reports with this command jest --coverage

Test Reports

If you don’t want to use the async function you need to use done as below.

calculator-done.test.js

You get the same output as above.

Test Outputs

Grouping Tests

It’s easy to maintain and understand when you group all the related tests together. Let’s see how we can do that with the Jest library. All you need to do is that you need to wrap all the tests that you want to group in describe function. Look at the example below, We have two groups of tests: one using async and another using the done function.

Group Tests

Here is the output when you run the above file.

output

Testing Errors

We have this file that contains three functions add, subtract and multiply. If you pass inputs other than numbers these functions throw errors. Let’s see how we can test these errors with the Jest library.

the calculator that throws an error

The Jest library provides its own assertion library for throws. You need to call the method on the function and assert the error.

Tests

Here is the output when you run the above file.

Output

Testing Callbacks

Let’s set up a simple server with express for testing. We have a simple express app with one endpoint and listens on port .

server.js

You need to have express and request-promise libraries installed to make this work.

npm install express request-promise// start the server
node server.js

We have a simple function which calls this endpoint as below. The first argument is the URL and it throws the error if the URL is wrong. Otherwise, it calls the URL and passes the data to the callback function.

callback.js

Let’s see how we can test the above callback function with the Jest library. We are passing the wrong URL in the first test and test for the error object that contains that particular string. The second has a valid URL and asserts the data returned in the callback.

callback.test.js

Here is the output when you run the above file.

output

Testing Promises

Here is a promise version of the above one. It returns the promise. If the URL is wrong it rejects otherwise it resolves the data by calling the endpoint.

promise.js

Let’s see how we can test the above promise function with the Jest library. We are passing the wrong URL in the first test and test for the rejecting object that contains that particular string. The second has a valid URL and asserts the data returned in the promise. We are using async/await here.

Promise Tests

Here is the output when you run the above file.

output

Setup/Teardown

There are some scenarios in which you have to set up some configuration such as database, etc before running the tests and clean up later. Jest provides the following four methods just for that.

Setup and Teardown

Reports

We have a lot of tests now in the project and we have already added an npm script to run the test. Once the Jest is installed, it has the test runner executable and the location of the test runner is node_modules/.bin/jest. You can add the npm scripts section of the package.json file as below. You need to run this with the flag --coverage

jest --coverage

I configured the npm scripts to run with the coverage.

npm script coverage added

You can run this command as well.

npm run coverage

Here are the reports.

Reports

Summary

  • Unit testing is as important as developing a project nowadays and it becomes an integral part of development.
  • It actually boosts the quality of the code and the confidence of developers.
  • There are so many libraries that can be used for unit testing in nodejs applications. Jest library is one of them.
  • First, we need to install the Jest library with the following command. Since we run unit tests mostly in the development phase, we need to use the flag --save-dev. Make sure you run this command in the root folder.
  • It’s easy to maintain and understand when you group all the related tests together.
  • You can add the test runner executable and the location of the test runner is node_modules/.bin/jest.
  • You can get the coverage with the flag --coverage

Conclusion

There are so many libraries that can be used for unit testing in nodejs applications. Jest library is one of them. According to their website, Jest is a delightful JavaScript Testing Framework with a focus on simplicity. Jest aims to work out of the box, config free, on most JavaScript projects.

Bachina Labs

Tutorials Ranging from Beginner guides to Advanced | Never…

Sign up for BB Tutorials & Thoughts

By Bachina Labs

Tutorials Ranging from Beginner guides to advanced on Frontend, Backend, Blockchain, Docker, k8s, DevOps, Cloud,AI, ML. Thank you for subscribing and let me know if you want me cover anything?  Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Bhargav Bachina

Written by

Software Architect — Sharing Experiences With Examples | Frontend, Backend, Blockchain, Docker, k8s, DevOps, Cloud,AI, ML | https://www.linkedin.com/in/bachina/

Bachina Labs

Tutorials Ranging from Beginner guides to Advanced | Never Stop Learning

Bhargav Bachina

Written by

Software Architect — Sharing Experiences With Examples | Frontend, Backend, Blockchain, Docker, k8s, DevOps, Cloud,AI, ML | https://www.linkedin.com/in/bachina/

Bachina Labs

Tutorials Ranging from Beginner guides to Advanced | Never Stop Learning

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store