To test a React app using Jest, you’ll need the right setup and tools to write, run, and validate your component and logic behavior effectively.
Overview
Steps to Test React Apps Using Jest: Quick Steps
- Set up React app: Create a new app using Create React App (CRA), which includes Jest by default.
- Install testing tools: Add @testing-library/react, @testing-library/jest-dom, and react-test-renderer.
- Configure Jest: Use setupTests.js or jest.config.js to add matchers and set the test environment.
- Write test files: Use describe, test, and expect to test rendering, behavior, and logic.
- Use RTL for UI testing: Render components and query elements using RTL’s render and screen.
- Run tests: Use npm test to run your test suite and verify component behavior.
This React Jest tutorial explains how to effectively test React apps using Jest.
What is Jest?
Jest is a powerful JavaScript testing framework developed by Meta, designed primarily for testing applications built with React.
It serves as both a test runner and an assertion library, offering everything needed to write, organize, and execute unit and integration tests.
Key features of Jest:
- Zero-config setup with Create React App and support for custom configurations
- Built-in assertion library for validating test outcomes
- Mocking capabilities to isolate components and test dependencies
- Snapshot testing for tracking UI changes over time
- Code coverage reports to measure test effectiveness
Jest integrates seamlessly with tools like React Testing Library (RTL), enabling developers to test components based on how users interact with them. This makes it the foundation of modern React testing workflows.
Also Read: Top Testing Libraries for React in 2025
Why use Jest to test React Apps?
Jest is the default testing framework for React applications—and for good reason. It works seamlessly with React Testing Library, offering a complete solution for testing components from a user’s perspective.
Key reasons to use Jest with React:
- Built into Create React App (CRA) for instant setup and zero configuration
- Full-featured ecosystem including assertions, mocking, timers, and snapshot testing
- Fast and parallel test execution for efficient feedback loops
- Powerful mocking utilities to isolate components and control dependencies
- Rich integration with React Testing Library, enabling tests that focus on behavior, not implementation details
Learn More: React Testing: How to test React components?
Together, Jest and React Testing Library form the backbone of modern, scalable React testing strategies.
Why Use Jest with React Testing Library?
The React Testing Library (RTL) focuses on testing components the way users interact with them through the DOM rather than their internal implementation.
Using Jest with React Testing Library provides a powerful, user-centric testing setup that ensures components behave correctly in real-world scenarios, with minimal configuration and a robust developer experience.
How to Test React Apps using Jest: Tutorial
Before you begin testing react apps, ensure your development environment is properly set up.
Prerequisites
- You must have Node.Js installed on your system at least version 14 or higher.
- Install any IDE of your choice. In this example, we are using Visual Studio Code IDE.
- You must be familiar with the basic concepts of React.Js.
Setting Up and Installing Jest
Jest can be easily configured in a React project created with Create React App (CRA).
It comes pre-integrated with CRA, but additional tools like React Testing Library and @testing-library/jest-dom enhance the testing capabilities.
Step 1: Create a React application
Use the following command to set up a new React app:
npx create-react-app basic-app
Start the development server:
npm start
Step 2: Install testing dependencies
npm install --save-dev @testing-library/react @testing-library/jest-dom react-test-renderer
- @testing-library/react: Enables DOM-based component testing.
- @testing-library/jest-dom: Provides additional matchers for assertions.
- react-test-renderer: Used for generating snapshots of components.
Step 3: Create a component for testing
Create the component to be tested at basic-app/src/components/HelloWorld.js:
import React from 'react'; function HelloWorld() { Â Â return ( Â Â Â Â <div> Â Â Â Â Â Â <h1>Hello World</h1> Â Â Â Â </div> Â Â ); } export default HelloWorld;
Update basic-app/src/App.js:
import React, { Component } from 'react'; import HelloWorld from './components/HelloWorld'; class App extends Component { Â Â render() { Â Â Â Â return <HelloWorld />; Â Â } } export default App;
Step 4: Run tests
Run the test suite from the project root:
npm test
This setup allows writing and executing unit, snapshot, and interaction-based tests using Jest and React Testing Library.
Configuring Jest
A jest.config.js file can be created at the project root to customize Jest beyond the default Create React App setup. Configuring jest includes specifying setup files and test environments.
Key configurations:
- setupFilesAfterEnv: Points to files that configure testing utilities like @testing-library/jest-dom for extended matchers.
- testEnvironment: Usually set to “jsdom” for browser-like testing.
- moduleNameMapper: Used to handle asset imports or CSS modules during tests.
Example configuration snippet in jest.config.js:
module.exports = { Â Â setupFilesAfterEnv: ['<rootDir>/src/setupTests.js'], Â Â testEnvironment: 'jsdom', };
The setupTests.js file typically imports @testing-library/jest-dom:
import '@testing-library/jest-dom';
This setup ensures Jest is properly configured to work seamlessly with React Testing Library and provides enhanced assertion capabilities.
Core Jest Concepts for React Testing
Understanding these fundamental Jest concepts is essential for writing effective and maintainable tests in React applications:
1. Writing Test Files:
Use describe to group tests, test or it to define cases, and expect for assertions.
2. Common Jest Matchers:
- toBe (strict equality)
- toEqual (deep equality)
- toBeTruthy (truthiness)
- toContain (array or string includes)
3. Using jest-dom Matchers:
- toBeInTheDocument (checks element presence)
- toHaveTextContent (verifies text content)
4. Mocking in Jest:
- jest.fn() creates mock functions
- jest.spyOn() monitors existing function calls
- Module mocking isolates components by replacing imports
5. Setup and Teardown Methods:
- beforeEach / afterEach: run before/after each test
- beforeAll / afterAll: run once before/after all tests
Mastering these core concepts helps ensure tests are organized, reliable, and easy to understand.
Testing React Components with Jest and React Testing Library
Testing React components effectively involves rendering, interacting, and verifying UI behavior using React Testing Library alongside Jest.
- Use render to display components in a test environment without a real browser.
- Find elements using queries like getBy, getAllBy, queryBy, and findBy—these let you search by role, text, or test ID, mimicking how users find things on the screen.
- Simulate user actions such as clicks and typing with fireEvent (basic events) and user-event (more realistic interactions).
- Test props by rendering components with different values and checking if the UI updates correctly.
- Check component state by looking at how the UI changes after certain actions, without testing state directly.
- Verify event handlers by triggering events and ensuring the expected changes happen.
- Test custom hooks separately using tools like @testing-library/react-hooks or the renderHook method to focus only on hook logic.
Unit Testing of React Apps using Jest
Unit testing checks individual functions or logic inside components in isolation. This ensures the code works correctly without dependencies or UI interference.
Example of unit testing a simple React component rendering:
import React from 'react'; import { render, screen } from '@testing-library/react'; import HelloWorld from '../components/HelloWorld'; test('renders the "Hello World" message', () => { Â Â render(<HelloWorld />); Â Â const helloWorldText = screen.getByText('Hello World'); Â Â expect(helloWorldText).toBeInTheDocument(); });
Snapshot Testing of React Apps using Jest
Snapshot testing captures the rendered output of a component and compares it to a saved snapshot. It quickly detects UI changes and helps prevent unintended updates.
Example of snapshot testing:
import React from 'react'; import renderer from 'react-test-renderer'; import HelloWorld from './HelloWorld'; it('matches the snapshot', () => { Â Â const tree = renderer.create(<HelloWorld />).toJSON(); Â Â expect(tree).toMatchSnapshot(); });
Snapshot tests are great for stable UI parts but can become brittle if overused. Use them as a secondary tool alongside other test types.
Testing Asynchronous Operations
Testing async code in React apps requires handling promises, waiting for UI updates, and mocking API calls effectively.
- Working with Promises and async/await: Use async/await in your tests to handle asynchronous operations cleanly and avoid callback hell.
- Using findBy Queries and waitFor: React Testing Library’s findBy queries return promises, ideal for waiting until elements appear. waitFor helps wait for specific UI changes before assertions.
- Mocking API Calls: Mock network requests using jest.mock for libraries like Axios or custom fetch functions to isolate tests from real APIs and control responses.
Learn More: Synchronous vs Asynchronous in JavaScript
Measuring Test Coverage
Measuring test coverage helps ensure your tests thoroughly exercise your React codebase, highlighting untested parts.
- Use Jest’s built-in coverage tool by running tests with the –coverage flag.
- Coverage reports show metrics like statements, branches, functions, and lines covered by tests.
- Integrate coverage checks into CI pipelines to enforce minimum coverage thresholds.
- Analyze reports to identify untested code and improve test completeness.
Learn More: How to ensure Maximum Test Coverage?
React Jest Tests with BrowserStack
BrowserStack enhances your React Jest testing with a real device cloud to test across multiple real devices and browsers in real user conditions to deliver a seamless user experience. It integrates easily with your workflows, making testing faster and more efficient.
- Run Jest tests across real browsers and real devices with BrowserStack Automate
- Integrate with popular CI/CD tools for automated cross-browser testing
- Access detailed logs, screenshots, and video recordings to debug failing tests
Ensure consistent test environments with BrowserStack’s cloud-based Selenium Grid
Best Practices for Testing React Apps with Jest
Adopting modern best practices ensures tests are maintainable, reliable, and focused on real user interactions.
- Write clear and descriptive test names that explain what the test verifies.
- Follow the Arrange-Act-Assert (AAA) pattern: set up test data, perform actions, then assert results.
- Test behavior and user outcomes rather than internal implementation details to avoid brittle tests.
- Keep tests isolated and independent to prevent flaky results and simplify debugging.
- Prefer queries like roles, text, or labels over data-testid for better accessibility testing; use data-testid only when no better selector is available.
Also Read: Understanding Jest Mock Hook
Debugging Jest Tests in React
Effective debugging helps quickly identify and fix failing tests for smoother development. Use Jest’s built-in error messages, test logs, and interactive watch mode. Combine these with React Testing Library’s debugging utilities like screen.debug() to inspect the rendered DOM.
Conclusion
The essential component of the software development sector is testing since it assures that users receive the best product, upholding the company’s reputation in the process. In this tutorial, we learned how to test using Jest in React applications.
Jest is a well-known JavaScript testing framework and is extensively used to test React applications due to several features, it does not require extensive configuration, strong community support, and seamless integration into React applications.
Moreover, we also came across a practical demonstration of how to implement Jest testing React applications. We saw two popular testing procedures, Unit Testing, and Snapshot testing. Snapshot testing is used to find any unintentional UI changes, whereas unit testing is used to test individual components of React applications by separating their interaction with other components or dependencies.
Follow-Up Read: How to Debug Jest Tests?
Useful Resources for Jest
- How to Debug Jest Tests?
- Understanding Jest Mock Hook
- How to Configure Jest
- it.each function in Jest
- Snapshot Testing with Jest
- How to write Snapshot Tests for React Components with Jest?
- How to Run Jest Tests for a Specific File/Folder
- Jest Framework Tutorial: How to use it?
- Understanding Testing Library Jest DOM
- Understanding Jest-Globals
- Unit Testing of React Apps using JEST : Tutorial
- How to test React App using Jest
- Understanding Jest beforeEach Function
- Performing NodeJS Unit testing using Jest
- Jest vs Mocha: Comparing NodeJS Unit Testing Frameworks
- Jest vs Mocha vs Jasmine: Which JavaScript framework to choose?