Skip to main content

Introduction

What is Jest?

Jest is a JavaScript testing library created by the same company behind React: Facebook. But while Jest was created by the same developers who created React, it is not limited to only React — it can also be used with other frameworks like Node, Angular, Vue.js, and Babel.

Jest is a great tool for testing, with many advantages that make it an ideal choice for both front-end and back-end testing. Its ease of use, time-saving features, and lack of dependence on third-party tools make it an attractive option.

Getting Started

Installation

Jest is a Node-based runner. This means that the tests always run in a Node environment and not in a real browser. This lets us enable fast iteration speed and prevent flakiness.

First of all, create a new project in React, Express, or any other Node.js framework. I am going to use simple node js for this doc.

First of all, create directory and initialize npm:

mkdir jest-demo
cd jest-demo
npm init -y

Now, install Jest:

npm install --save-dev jest

For TypeScript, you'll need to install ts-jest and @types/jest types:

npm install --save-dev ts-jest @types/jest

Test File Setup

Jest will look for test files with any of the following popular naming conventions:

  • Files with .js, .jsx, .ts or .tsx suffix in __tests__ folders.
  • Files with .test.js, .test.jsx, .test.ts or .test.tsx suffix.
  • Files with .spec.js, .spec.jsx, .spec.ts or .spec.tsx suffix.

The __tests__ folder name is special. Jest will consider files in __tests__ folders as tests, so you can store test files anywhere you want.

Writing Tests

To create a test, add an test function (also known as a test case) to the test. Let's say, we have a function that adds two numbers. We could test it like this:

math.test.js
// sum function
function sum(a, b) {
return a + b;
}

// test case for sum function
test("addition should return 4", () => {
const a = 2;
const b = 2;

expect(sum(a, b)).toBe(4);
});

This is your standard test call (you can also use test). If we analyze this, it is a function that receives two arguments:

  • a string for the test description
  • a callback function that will be called when the test runs. on expect we are checking whether the math function gives the correct result.

Running Tests

To run the test, we can use the npx jest command. This will run all the tests in the project.

npx jest

By default, Jest will look for files matching the above mentioned naming convention. To run a specific test, we can use the npx jest <test-file-name> command.

npx jest math.test.js

Watch Mode

Jest can be run in watch mode. In this mode, Jest will watch for changes in the files and run the tests again. To run Jest in watch mode, we can use the npx jest --watch command.

npx jest --watch

Coverage

Coverage is a measure of how much of our code is covered by tests. Jest can also generate coverage reports. To generate a coverage report, we can use the npx jest --coverage command.

npx jest --coverage

This will generate a coverage report in the coverage folder.

Assertions

Jest uses the expect function to make assertions. An assertion is a way to test the result of a function.

math.test.js
// sum function
function sum(a, b) {
return a + b;
}

// test case for sum function
test("addition should return 4", () => {
const a = 2;
const b = 2;

expect(sum(a, b)).toBe(4);
});

In the above example, we are using the toBe matcher to check whether the result of the sum function is 4.

Common Matchers

Jest has a lot of matchers that can be used to make assertions. Here are some of the most common matchers:

  1. toBe()
  2. toEqual()
  3. not.toBe()
  4. toContain()
  5. toBeNull()
  6. toBeUndefined()
  7. toHaveLength()
  8. toThrow()
  9. toMatch()

toBe()

Checks if the result of a function is equal to the expected value using strict equality (===).

test("add function should correctly add two numbers", () => {
const result = add(2, 3);
expect(result).toBe(5);
});

toEqual()

Verifies deep equality between the result of a function and the expected value.

test("calculateTotal should return correct object", () => {
const cart = [10, 20, 30];
const result = calculateTotal(cart);
expect(result).toEqual({ total: 60 });
});

not.toBe()

Ensures that the result of a function is not strictly equal to the expected value.

test("subtract function should not return incorrect value", () => {
const result = subtract(10, 5);
expect(result).not.toBe(10);
});

toContain()

Verifies if an array, string, or iterable object contains the specified element or substring.

test("shopping cart should contain the added item", () => {
const cart = ["apple", "banana", "orange"];
const newItem = "pear";
cart.push(newItem);
expect(cart).toContain(newItem);
});

toBeNull()

Checks if the result of a function is null.

test("should return null", () => {
const result = null;
expect(result).toBeNull();
});

toBeUndefined()

Checks if the result of a function is undefined.

test("should return undefined", () => {
const result = undefined;
expect(result).toBeUndefined();
});

toHaveLength()

Checks if a string, array, or object has the specified length property.

test("string length should be equal to the specified length", () => {
const str = "Hello, World!";
expect(str).toHaveLength(13);
});

toThrow()

Ensures that a function throws an error when it is invoked.

test("divide function should throw an error when dividing by zero", () => {
const divideByZero = () => divide(10, 0);
expect(divideByZero).toThrow();
});

toMatch()

Verifies if a string matches the specified regular expression pattern.

test("email should match the regular expression pattern", () => {
const email = "test@example.com";
expect(email).toMatch(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}$/);
});

These examples illustrate how to use different Jest matchers to perform assertions and validate the expected behavior of functions and values in your tests. By utilizing these matchers appropriately, you can effectively test your code and ensure its correctness.

Code

You can find the code for this doc from here