Testing with Jest: Comprehensive Guide

Melih Yumak
4 min readJun 4

Table of Contents

  1. Introduction to Jest
  2. Installation and Setup
  3. Writing Your First Test
  4. Test Matchers
  5. Asynchronous Testing
  6. Testing React Components
  7. Snapshot Testing
  8. Mock Functions
  9. Conclusion

1. Introduction to Jest

Jest is a powerful JavaScript testing framework developed by Facebook. It’s known for its “zero-configuration” philosophy and is designed to work seamlessly with most JavaScript projects and frameworks, including React. With Jest, you can write tests with an approachable, familiar, and feature-rich API that gives you results quickly.

2. Installation and Setup

Before getting started with Jest, you need to install it. We can setup Jest for our javascript applications by running the following command in your terminal as below

npm install --save-dev jest

Next, you will have to set up a test script in your package.json file:

"scripts": {
"test": "jest"

With this setup, you can now run your tests using npm test

3. Writing Your First Test

Let’s start by writing a simple test. Assume we have a function sum in a file called sum.js

function sum(a, b) {
return a + b;

To test this function, create a new file in the same directory called sum.test.js. Jest automatically recognizes .test.js files as test files. In sum.test.js, import the sum function and write the test:

const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);

You can now run this test with npm test, and Jest will print this message if the test passes: PASS ./sum.test.js

4. Test Matchers

Jest uses matchers to let you test values in different ways. The .toBe matcher used above checks for exact equality. If you want to check the value of an object, you should use…