Testing react components with Jest

Key takeaways:

  • Jest is a popular testing framework for React applications due to its simplicity, flexibility, and extensive features.

  • Jest offers features like zero-configuration, snapshot testing, mocking, parallel testing, and code coverage.

  • Setting up Jest in a React project is straightforward, especially with Create React App.

Testing is an essential aspect of modern web development, ensuring that applications behave as expected and are free from bugs. Jest is one of the most popular testing frameworks for React applications due to its simplicity, flexibility, and extensive features. We’ll discuss the testing of React components with Jest, covering everything from setup and basic testing techniques to advanced topics such as mocking, snapshot testing, and testing asynchronous behavior.

What is Jest?

Jest is a JavaScript testing framework developed by Facebook. It is designed to ensure the correctness of any JavaScript codebase. Because of its powerful features, such as zero-configuration, built-in mocking, and snapshot testing, it is particularly well-suited for testing React applications.

Let’s discuss some of the key features of Jest as follows:

  • Zero configuration: Jest works out of the box with minimal setup.

  • Snapshot testing: Captures the rendered output of our components and compares it to previous outputs.

  • Mocking: Allows us to replace dependencies with mock implementations.

  • Parallel testing: Runs tests in parallel to improve performance.

  • Code coverage: Provides built-in support for measuring code coverage.

We’re now familiar with the key features of Jest; now it’s time to set it up in a React project.

Setting up Jest in a React project

Setting up Jest in a React project is straightforward, especially if we use Create React App, which comes with Jest pre-configured. If we’re starting a new project, we can create it with Create React App command, and Jest will be ready to use.

Testing React components with Jest involves setting up Jest as the testing framework and writing test cases to ensure our components behave as expected. Here’s a step-by-step guide to get us started:

Setting up our environment

If we don’t already have a React app, we can create one using Create React App as follows:

npx create-react-app my-app
cd my-app

To run our tests, we’ll be using the following command:

npm test

Writing our first test

Testing our React components with Jest is straightforward and powerful. Let’s walk through writing our first test to understand the basic concepts and setup. Here’s an example of how to write a test for a simple button.js React component.

import React from 'react';
const Button = ({ onClick, label }) => (
<button onClick={onClick}>{label}</button>
);
export default Button;
Button.js component

This is a simple button component that takes two props: label and onClick. The label prop is used as the button text, and onClick is an event handler for click events. Now, let’s write its test case using Jest as follows:

import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import Button from './Button';
test('Button renders with correct label', () => {
const { getByText } = render(<Button label="Click me" />);
expect(getByText('Click me')).toBeInTheDocument();
});
test('Button triggers onClick event', () => {
const handleClick = jest.fn();
const { getByText } = render(<Button label="Click me" onClick={handleClick} />);
fireEvent.click(getByText('Click me'));
expect(handleClick).toHaveBeenCalledTimes(1);
});

Code explanation

Let’s explain the line-wise explanation of the test component file as follows:

  • Lines 1–4: We import React because we are working with React components. render and fireEvent are imported from @testing-library/react to render our component and simulate user interactions, respectively. The @testing-library/jest-dom/extend-expect import is for using custom matchers like toBeInTheDocument().

  • Lines 6–16: Each test function contains a single test case. The description (first argument) explains what the test is verifying. render renders the component into a virtual DOM for testing. It returns utility functions, like getByText, to query the rendered output. We use expect to make assertions about the component’s behavior. For example, expect(getByText('Click me')).toBeInTheDocument() asserts that a button with the text "Click me" is in the document. jest.fn() creates a mock function, allowing us to track if and how the function is called. This is useful for testing event handlers like onClick. The fireEvent simulates user events. Here, fireEvent.click simulates a click on the button, allowing us to test if the onClick handler is called correctly.

Running tests

Click the “Run” button in the widget below and run our tests, use the following command in our terminal:

npm test

This command starts Jest in watch mode, running tests related to changed files and watching for further changes.

AAABAAQAEBAAAAEAIADjAQAARgAAABgYAAABACAADAMAACkCAAAgIAAAAQAgADkDAAA1BQAAQEAAAAEAIACwBgAAbggAAIlQTkcNChoKAAAADUlIRFIAAAAQAAAAEAgDAAAAKC0PUwAAAORQTFRFIiIiIiIiIiIiIiIiIiIiIiIiMlBYPXKAKTc7Kjo+SJCkLUJHRYiaOGRvNVhiNltlS5muS5qvMU1VOWdzM1NcSZOnOmd0JzAzQHuLVrnUVLTPQX2NVrvWQHmJNlxmSJKmLUNJSZSoRYibKztAN19pN19qRoqdSparS5uwSJCjLUJIYdr7LEBGQ4OUTJ2zJi4wV73ZTqO6SZOoJCkrQoGRSpWqUq/IP3aGPnOBPnWEU7HKPXF/UKnBUKjAUKe/LD9ENFVeJSstTaC2S5iuJSssMk9YKzxBTJyyIyYmRIaYJSwuSZWpdvRU9gA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w9zLK6zqIMDZSLXXSxK1cUcy25OS0vLU2UiMNxkaaszbS8bdy1YGt7HWY5o1t4vDCf56HSfFpfgEglsX8oMOPc1D+IrEAC/OfvA1laXnlo8tQmuDjyvKSp6Gc3dIsU11VprpWhRuq1pSprlqm6m/r6xu3eHrjmeLGU25trHvaundh2YTPHoXFu7Td9ShtZy+u/uW9wL+8+wWMW6cIGBlis7UXcbbFJtWvB7mQJBbxesiKF4sESD5hzEtUMS/m+DFPgokwvi5/aAfNh1n+QdP2owot6j7bi7qroljVou5936jrDNvROwfD9k60f9h2xf2Pzrj/MQCN69fET0Amdi/E/l+X9lz0Dsdc7S4Pmb0rMJQDOxwUASEGZsoMEKa00yXCIEpZt0+Uwo4nL8VdX4o73xDAJyImTqpuCWERUZBeABmUY3imQeHSAAAAAElFTkSuQmCC
Testing react components with Jest

Conclusion

Testing is a critical part of modern web development. It ensures that applications perform as expected and are free of bugs. We learned how to set up Jest in a React project, write our first test for a simple button component, and run our tests to verify our component’s behavior. With a well-organized file structure and a thorough understanding of Jest’s features, we can effectively test our React components, ensuring they function correctly and are maintainable over time. Try implementing these steps in your own React projects to enhance the reliability and quality of your applications. Happy testing!

Frequently asked questions

Haven’t found what you were looking for? Contact Us


Can Jest be used for React?

Yes, Jest is specifically designed for testing React applications. It offers many features that make it well-suited for React, such as:

  • Zero-configuration: Jest works out of the box with minimal setup.
  • Snapshot testing: Captures the rendered output of React components and compares it to previous outputs.
  • Mocking: Allows you to replace dependencies with mock implementations.
  • Parallel testing: Runs tests in parallel to improve performance.
  • Code coverage: Provides built-in support for measuring code coverage.

Which is better, Cypress or Jest?

The choice between Cypress and Jest often depends on your specific testing needs and preferences. Both are excellent tools, but they have different strengths and approaches:

Cypress is used for:

  • End-to-end testing framework.
  • Focuses on testing the entire application workflow, including interactions with the browser and network.
  • Has built-in time travel and automatic waiting features.

Jest is used for:

  • Unit and integration testing framework.
  • Focuses on testing individual components or modules in isolation.
  • Provides a more granular level of control and flexibility.

What is the difference between a jest and React testing library?

  • Jest: A JavaScript testing framework that provides a comprehensive set of features for testing JavaScript code, including React components.
  • React testing library: A library built on top of Jest that provides a set of utility functions specifically designed for testing React components. It focuses on testing components from the user’s perspective, making your tests more maintainable and reliable.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved