Jest: make your code more secure and reliable

image: jest

porGabriel Dürr M., São Paulo - SP

If you develop in React, you've probably heard of Jest - one of the most popular tools for testing JavaScript. Jest is easy to use and offers a wide range of features for testing components, functions and libraries. In the content of these posts, you will be shown how to install and configure Jest and react-testing-library, and how to write tests for your projects.

Introduction to Jest - What is Jest and why use it?



Jest is designed to be easy to use and offers powerful features for testing JavaScript projects, including support for asynchronous tests and integration tests. It is very popular among React developers as it has easy integration and offers a variety of features for testing React components.

Jest is also fast, which means you can run your tests faster than with other testing frameworks. Jest runs tests in parallel, which can save time on larger projects. In addition, Jest has an intuitive syntax that makes creating tests simpler and easier to understand.

Installing Jest and the React Test Library

Before you can start using Jest, you'll need to install it in your project. Fortunately, installing Jest is simple and quick. First, you'll need to install Node.js on your computer if you haven't already.

After installing Node.js, you can install Jest using npm. Just open the terminal and type the following command:

npm install --save-dev jest @testing-library/react @testing-library/jest-dom

Configuring Jest in your project

Agora que o Jest está instalado em seu projeto, você precisa configurá-lo. Você pode configurar o Jest adicionando um arquivo de configuração na raiz do seu projeto chamado jest.config.js. Este arquivo permite que você configure várias opções para o Jest, como o diretório de arquivos de teste, o padrão de nomenclatura para arquivos de teste e outras opções.

Here is a basic example of a configuration file:

module.exports = {
  testMatch: ["**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)"],
  testPathIgnorePatterns: ["/node_modules/"],
};
gbdx-logo

    • This configuration file tells Jest to look for test files in the tests directory and in any files that end in .spec.js or .test.js. It also tells Jest to ignore the node_modules directory.

Basics of Testing with Jest

Create a file called sum.test.js in the tests directory. Add the following code to the file:

function sum(a: number, b: number) {
	return a + b;
}


test("adds 1 + 2 to equal 3", () => {
	expect(sum(1, 2)).toBe(3);
});
gbdx-logo

    • This test verifies that the sum function correctly adds two numbers. The test is run using Jest's test function. The test function takes two arguments - a description of the test and a function containing the test logic. The test function uses Jest's expect function to check whether the output of the sum function equals 3.

To run the test, open a terminal and run the following command:

npm run test

    • This command starts Jest and runs all the tests in your project. You'll see output from Jest in the terminal, which will show you whether the test passed or failed.

Testing React components with Jest and @testing-library/react

Jest is widely used for testing React applications. To test React components with Jest, you can use the @testing-library/react test library. This library provides functions to simulate user events, access DOM elements and check component state.

Here is an example of testing a React component using @testing-library/react:

import { Button } from "@components/button";

import { render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";


describe("Button", () => {
	it("renders a button", () => {
		const { getByText } = render(<Button label="Click Me" />);

		const button = getByText("Click Me");

		expect(button).toBeInTheDocument();
	});

	it("calls onClick when button is clicked", () => {
		const onClick = jest.fn();
		const { getByText } = render(<Button label="Click Me" onClick={onClick} />);

		const button = getByText("Click Me");

		userEvent.click(button);

		expect(onClick).toHaveBeenCalled();
	});
});
gbdx-logo


    • This test verifies that a Button component renders correctly and that the onClick function is called when the button is clicked. The test uses the @testing-library/react render function to render the Button component. It uses the getByText function to get the button's DOM element and the userEvent function to simulate a button click. It uses the jest.fn function to create a mock function for onClick and the toHaveBeenCalled function to check if the mock function was called.

Jest component simulation

Sometimes you may need to isolate a component during a test and mock one or more of its children. Jest provides an easy way to do this using the jest.mock function

Here is a test example that simulates a child component in a parent component:

import Parent from "@components/button";

import { render } from "@testing-library/react";

jest.mock("./Child", () => <div>Mock Child Component</div>);

test("renders the parent component with a mocked child", () => {
	const { getByText } = render(<Parent />);

	const child = getByText("Mock Child Component");
	expect(child).toBeInTheDocument();
});
gbdx-logo

    • This test simulates a Child component on a Parent component. It uses the jest.mock function to replace the Child component with a mock component. The test uses the render function to render the Parent component and the getByText function to get the mock child component's DOM element.

Testing React button components step by step

Button components are common in React apps and can be easily tested with Jest. Here's a step-by-step guide to testing button components with Jest:

  1. Create a file called Button.test.js in the tests directory.
  2. Import the Button component and the @testing-library/react test library.
  3. Write a test that verifies that the Button component renders correctly.
  4. Write a test that checks if the onClick function is called when the button is clicked
  5. Write a test that checks whether the button is disabled when the disabled property is set to true.

Here is a code example for testing a button component:

import Button from "./Button";

import { render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

describe("Button", () => {
	it("should be renders a button", () => {
		const { getByText } = render(<Button label="Click me" />);

		const button = getByText("Click me");
		expect(button).toBeInTheDocument();
	});

	it("should be calls onClick when button is clicked", () => {
		const onClick = jest.fn();
		const { getByText } = render(<Button label="Click me" onClick={onClick} />);

		const button = getByText("Click me");
		userEvent.click(button);
		expect(onClick).toHaveBeenCalled();
	});

	it("should be disables the button when disabled is true", () => {
		const { getByText } = render(<Button label="Click me" disabled />);

		const button = getByText("Click me");
		expect(button).toBeDisabled();
	});
});
gbdx-logo

    • This code tests that the Button component renders correctly, that the onClick function is called when the button is clicked, and that the button is disabled when the disabled property is set to true.

Jest Test Coverage

Jest provides a code coverage tool that helps you verify that your tests are covering all of your code. Code coverage is a measure of the percentage of code that is executed while running tests. The higher the code coverage, the more likely you are to find bugs in your code.

    • To use Jest's code coverage tool, run the following command in the terminal:

npm run test -- --coverage

    • This command starts Jest and runs all the tests in your project and generates a code coverage report. You can open the coverage/lcov-report/index.html file in your browser to see the code coverage report

Advanced Jest Techniques

Jest provides many advanced features for testing such as parallel testing, real-time testing, and integration testing. Here are some tips for using these advanced features:

    • Use Jest's --watch option to run tests in real time while you make code changes.
    • Use Jest's --coverageThreshold option to set minimum code coverage thresholds.
    • Use Jest's --maxWorkers option to run tests in parallel across multiple processes.
    • Use the supertest test library to test Node.js APIs.

Conclusion

Jest is an easy-to-use and widely used JavaScript testing framework for testing React applications. In this article, we've seen how to install and configure Jest and the React test library, how to write basic and advanced tests with Jest, and how to use advanced features like parallel testing and code coverage. I hope this article helps you become a Jest master and write quality tests for your JavaScript applications.

If you want to learn more about Jest and the React test library, visit Jest's official documentation and its's from @testing-library/react

recent posts
ReactJS 18 guide for beginners
image: reactjs banner
Next.js: The React Framework of the Future
image: Nextjs Banner
my logo

© Designed & Built by Gabriel Dürr M. 🖤