Unit Testing of React Apps using JEST : Tutorial

Related Product On This Page What is Unit Testing in React?January 26, 2026 · 13 min read · Testing Guide

Related Product

Unit Testing of React Apps using JEST: Tutorial

Unit testing in React applications using Jest aid you control that your components act as intended and is bug-free.

Overview

What is Unit testing React with Jest?

Unit testing React with Jest refers to the testing of individual factor or functions of a React covering in isolation using the Jest testing framework to corroborate their expected functionality.

What to test in Unit Testing for React Apps?

  • Component rendering
  • State and property
  • Event handling
  • Lifecycle method

Benefits of Unit Testing of React Apps using JEST

  • Faster Feedback Loop
  • Isolated Testing of Components
  • Built-in Test Runner and Assertions
  • Snapshot Testing Support:
  • Mocking Capabilities
  • Enhanced Code Quality and Maintainability

In this guide, you will learn in particular about unit examination of react apps using JEST, cover requirement, implementation, benefits, best practices and more.

What is Unit Testing in React?

Unit testing is a character of testing where case-by-case units or components of software are tested. In the context of React applications, a unit could be a React component, a help function, or any other JavaScript faculty. The finish is to verify that each unit of the software performs as designed.

What is Unit testing React with Jest?

Unit screen React with Jest refers to testing individual part or functions of a React application in isolation using the Jest testing fabric to validate their expected functionality.

It helps verify that each unit (like a button component) performs as intended without bank on other parts of the app.

Read More:

Why Unit Testing in React is significant?

Unit examination is important for several reasons:

  • It help in maintain codification calibre and assure that modules behave as expected.
  • It makes the process of debugging easier and quicker.
  • It serves as documentation, cater a detailed description of the scheme ’ s design and functionality.

What to test in Unit Testing for React Apps?

In a React application, we can prove respective aspects such as:

  • Component rendering:Ensure that the part render correctly under different weather.
  • State and prop: Test the state changes and the props being incur.
  • Event handling:Check if the case (like click, and input modification) are handled right.
  • Lifecycle methods: Validate if the lifecycle methods are working as expected.

Prerequisite (Project Setup) of React Unit Testing in JEST

Before starting with testing, a project setup is take. Here are the steps for the like:

1. Install Node.js and npm

Node.js is a JavaScript runtime that is command to run React applications. npm (Node Package Manager) is a software handler for Node.js. It can be downloaded and installed from the official Node.js website.

2. Create a new React application

Once Node.js and npm are installed, a new React application can be created using thecreate-vite command. The following dictation can be run in the terminal or command prompting:

npm init vite @ latest jest-react-app -- template react

This dictation creates a new directory named jest-react-app with a new React application.

3. Navigate to the task directory

The current directory can be changed to the newly created React application directory:

cd jest-react-app

4. Install Jest and jest-axe

Jest can be establish as a development colony using the following command:

npm install -- save-dev jest jest-axe

5. Verify Installation

The installation of Jest can be verify by running the following command:

npx jest -- version

This dictation should print the installed version of Jest.

6. Install other involve habituation

Install Axios package

npm i axios

7. Setup running environment

a) Run the following command to install dev habituation:

npm i –save-dev @ babel/preset-react @ babel/preset-env @ testing-library/jest-dom jest-environment-jsdom

b) Create babel.config.js file at the root of the project and glue the undermentioned code:

module.exports = {presets: [[' @ babel/preset-env ', {targets: {node: 'current ',},},], ' @ babel/preset-react ', // Adds support for JSX], plugins: [],};

c) Create jest.config.js file at the root of the labor:

module.exports = {testEnvironment: `` jsdom '', transform: {'^.+\\. (js|jsx|ts|tsx) $ ': 'babel-jest ',}, setupFilesAfterEnv: [' @ testing-library/jest-dom '],};

d) Update package.json

Add “ test ” command in the package.json file,

`` scripts '': {//other scripts '' test '': `` jest ''},

SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses.

How to perform Unit prove of React Apps using JEST?

Unit testing involves make examination causa for component and go them using Jest. Here are the high-level stairs:

  • Identify what to test:Determine the functionality that needs to be tested. This could be a function, a component, or an entire feature.
  • Write the test:Write a test that tab if the identified functionality work as expected. This involves limit up the necessary environs, fulfil the functionality, and checking the result.
  • Run the trial:Use Jest to run the test and ensure if it passes or fails.
  • Analyze the event:If the examination fail, analyze why it failed and fix the issue. If it passes, move on to the following functionality to test.

React Testing Library is a lightweight result for testing React components. It provides simple and complete React DOM testing utilities that encourage good examination drill. The master usefulness involve querying for thickening in a way that ’ s alike to how users would encounter them. This means tests will be more maintainable and resilient to component structure or styling changes.

Here ’ s an representative of a uncomplicated test causa habituate Jest and the React Testing Library:

import React from 'react '; import {render, blind} from ' @ testing-library/react '; import App from './App '; trial ('renders learn react tie ', () = & gt; {render (& lt; App / & gt;); const linkElement = screen.getByText (/learn react/i); await (linkElement) .toBeInTheDocument ();});

This test checks if the App component furnish a link with the text ‘ learn react ’. This is a simple illustration of how the React Testing Library can be used with Jest to write unit tryout for React applications.

Mocking Data in React Unit Testing with Jest

Mocking in unit testing is like apply stand-ins or substitutes for the real parts of your code. This helps you control and assure how these parts behave during testing, making your examination more dependable and easier to deal.

Jest, a testing creature, has built-in characteristic that let you create these substitutes for any piece of your codification, from simple functions to complex portion. This is especially handy when you ’ re testing parts of your codification that need information from outside sources like APIs.

Here ’ s an instance of how to mock data with Jest in a React application:

Consider a User component that fetch user data from an API when it ’ s mount:

// User.js importee React, {useEffect, useState} from 'react '; import axios from 'axios '; const User = () = & gt; {const [user, setUser] = useState (null); useEffect (() = & gt; {const fetchData = async () = & gt; {const response = await axios.get ('https: //api.example.com/user '); setUser (response.data);}; fetchData ();}, []); if (! user) {homecoming 'Loading ... ';} return & lt; div & gt; {user.name} & lt; /div & gt;;}; export default User;

Now, let ’ s write a test for this component, mocking the axios module to control the datum that ’ s returned by the API:

// User.test.js signification React from 'react '; meaning {render, screen, waitFor} from ' @ testing-library/react '; import axios from 'axios '; import User from './User '; // Mocking axios faculty jest.mock ('axios '); test ('fetches and displays user data ', async () = & gt; {// Create a mock response const mockResponse = {data: {name: 'John Doe '}}; axios.get.mockResolvedValue (mockResponse); // Render the User component render (& lt; User / & gt;); // Check if the mocked response is used in the component const userNameElement = await waitFor (() = & gt; screen.getByText (/John Doe/i)); expect (userNameElement) .toBeInTheDocument ();});

In this test, the axios faculty is mocked using jest.mock (). Then, a mock reply is created and axios.get is set to return this mock reply when called. The User portion is then rendered, which is expected to name axios.get and use the regress data. Finally, it ’ s checked if the user name from the mock reply is present in the document.

Code Coverage during React Unit Testing using Jest

Code coverage is a quantity of the extent of codification that is covered by tests. It ’ s a useful metric that can help understand the degree to which the application is test. Jest can return a code reporting report by adding the & # 8211; coverage iris to the test command.

Here ’ s how the code coverage for the User element examination from the previous example can be found:

1. Update the test command:

In the package.json, add the test dictation in the scripts section.

`` hand '': {'' test '': `` jest -- coverage '', // former scripts ...}

2. Run the tests:

The tests can be run with the updated dictation:

npm run test

3. Check the coverage report:

After the tests have run, Jest will output a codification coverage report in the terminal. This report will show the percentage of the code that is continue by tests.

Performance Optimization in React Unit Testing

Performance optimization in testing refers to improving the speed and efficiency of your test suite. Here are some strategies that can be used to optimize the performance of examination:

  • Avoid unnecessary rendering:In React, unnecessary rendering can slow down your tests. Make sure to only render the components that are necessary for the test.
  • Use shallow rendering:Shallow rendering is a characteristic provide by library like enzyme that renders a component “ one stage deep ” and prevents unneeded rendering of child components.
  • Mock out heavy colony:If your component depends on other components or modules that are heavy or dense (like network requests), consider mocking them out use Jest ’ s mocking features.
  • Run tests in latitude:Jest scarper tests in parallel by default, which can significantly speed up the test suite. Make certain your tests are not dependent on each other, so they can run in any order.
  • Limit the turn of snapshots:While snapshot tests can be useful, they can also slow down your examination suite and make it harder to conserve if overuse. Consider limiting the routine of snapshot tests, and prefer denotative assertion whenever possible.

Accessibility Testing in React using Jest Axe

Accessibility testing ensures that your covering is usable by all people, including those with handicap. Jest Axe is a library that integrates with Jest and allows you to run handiness cheque on your React part using the Axe accessibility testing locomotive.

Here ’ s an example of how to use Jest Axe for accessibility examination:

//Input.js import React from 'react '; import PropTypes from 'prop-types '; const Input = ({label, ... props}) = & gt; {return (& lt; div & gt; & lt; label htmlFor= '' input-field '' & gt; {label} & lt; /label & gt; & lt; input {... props} / & gt; & lt; /div & gt;);}; Input.propTypes = {label: PropTypes.string.isRequired,}; export default Input; //Input.test.js significance React from 'react '; import {render} from ' @ testing-library/react '; significance {axe, toHaveNoViolations} from 'jest-axe '; import Input from './Input '; // Add a Jest matcher to ensure for approachability trespass expect.extend (toHaveNoViolations); examination ('Input component should have no availableness violations ', async () = & gt; {const {container} = render (& lt; Input label= '' Test input '' / & gt;); const upshot = expect axe (container); // Assert that there are no accessibility violations expect (effect) .toHaveNoViolations ();});

In this test, the Input component is furnish with a label. Then, the axe function from jest-axe is habituate to run accessibility check on the rendered factor. Finally, the toHaveNoViolations matcher from jest-axe is used to assert that there are no accessibility violations.

Talk to an Expert

Common Challenges and Solutions of Testing React Apps with Jest

Given below are the challenges of test React Apps with Jest and ther solution:

1. Testing behavior that look on crotchet can be tricky, particularly when it come to effects and asynchronous updates.

Solution: Use utilities from React Testing Library like waitFor and act ()

importee {waitFor} from ' @ testing-library/react ';

2. React ingredient can rely on external APIs or services. Testing these without existent calls is crucial.

Solution: Leverage jest.mock () to mock modules, functions, or network cry.

jest.mock (' .. /api/fetchUser ');

3. Tests may fail or pass inconsistently if async operations aren & # 8217; t managed aright.

Solution: Useasync/await, waitFor, or findBy *query to handle async behavior properly.

4. Snapshots can fail still for small, intentional UI alteration.

Solution: Update snapshots solely when changes are designed viaukey in watch fashion or:

jest -u

Read More:

Advanced Testing Techniques [With Example]

Here are the advanced testing proficiency that can used for unit testing of React Apps using Jest:

Snapshot examination:

Snapshot testing captures the rendered output of a React component and saves it as a snapshot file. During later test runs, Jest compares the current output to the saved snapshot to spot unexpected UI changes.

// Button.js const Button = ({label}) = & gt; & lt; button & gt; {label} & lt; /button & gt;; export default Button;
// Button.test.js import React from 'react '; import {interpret} from ' @ testing-library/react '; importee Button from './Button '; test ('renders Button correctly ', () = & gt; {const {asFragment} = render (& lt; Button label= '' Click Me '' / & gt;); expect (asFragment ()) .toMatchSnapshot ();});

In the first run, the output is save by Jest. Later, if the output modification, the examination will miscarry

Read More:

Testing Props and State

This technique verifies a component & # 8217; s behavior when different property are legislate or its internal state changes. It sees to it that the component responds properly to different input scenarios and updates as expected.

// Counter.js signification {useState} from 'react '; const Counter = () = & gt; {const [count, setCount] = useState (0); return (& lt; div & gt; & lt; p & gt; {count} & lt; /p & gt; & lt; button onClick= {() = & gt; setCount (counting + 1)} & gt; Increment & lt; /button & gt; & lt; /div & gt;);}; export default Counter;
// Counter.test.js import React from 'react '; import {render, fireEvent} from ' @ testing-library/react '; import Counter from './Counter '; test ('increments counter on click ', () = & gt; {const {getByText, getByTestId} = render (& lt; Counter / & gt;); fireEvent.click (getByText ('Increment ')); expect (getByTestId ('count-value ') .textContent) .toBe (' 1 ');});

This see if the part ’ s state (count) update aright when the button is clicked.

Benefits of Unit Testing of React Apps using JEST

Here are the benefits of unit testing React apps using Jest:

  • Faster Feedback Loop: Since Jest is optimize for speed, teams can fulfill examination chop-chop and quickly identify and fix issues.
  • Isolated Testing of Components: Unit tests focus on item-by-item functions or components. Thus, you can ensure that each factor of the app use as wait.
  • Built-in Test Runner and Assertions: Jest is a comprehensive testing framework that has a test runner, assertion library, and mock potentiality. You don & # 8217; t get to integrate multiple library as Jest works out of the box.
  • Snapshot Testing Support: Jest offers snapshot testing to facilitate point unexpected UI changes.
  • Mocking Capabilities: Jest facilitates easy mocking of functions, modules, and API calls, driving contain testing of components in isolation.
  • Enhanced Code Quality and Maintainability: Unit exam with Jest ensure code plant as expected and advance clean, modular code. This create it easier to refactor part without breaking functionality.

Read More:

Best Practices for testing React Apps with JEST

Here are the best practices for testing React app with Jest:

  • Write clear, descriptive test cases.
  • Test the element behavior, not execution detail.
  • Keep tests isolated and autonomous of each other.
  • Regularly update tests when update constituent functionality.

Conclusion

Unit examination is a vital part of software ontogeny. It ensures code works as expected and help maintain high-quality standards. With Jest and React, comprehensive unit trial can be written that help build robust, reliable web applications.

By desegregate with tools like BrowserStack, teams can too test their React components across existent browsers and devices, ensuring consistent execution and UI conduct in real-world conditions.

Frequently Asked Questions

1. Is Jest for unit testing or integrating testing?

Jest is chiefly used for unit testing, but it indorse integration examine and basic end-to-end testing too.

2. How do you skip unit test in Jest?

You can use.skip modifieron a examination to skip unit test in Jest

test.skip ('should not run this trial ', () = & gt; {// This code will not run expect (true) .toBe (mistaken);});

Utilitarian Resources for Jest

Tags

On This Page

30,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free