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
Unit testing in React applications using Jest aid you control that your components act as intended and is bug-free. 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? Benefits of Unit Testing of React Apps using JEST In this guide, you will learn in particular about unit examination of react apps using JEST, cover requirement, implementation, benefits, best practices and more. 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. 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: Unit examination is important for several reasons: In a React application, we can prove respective aspects such as: 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: 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: 4. Install Jest and jest-axe Jest can be establish as a development colony using the following command: 5. Verify Installation The installation of Jest can be verify by running the following command: This dictation should print the installed version of Jest. 6. Install other involve habituation Install Axios package 7. Setup running environment a) Run the following command to install dev habituation: b) Create babel.config.js file at the root of the project and glue the undermentioned code: c) Create jest.config.js file at the root of the labor: d) Update package.json Add “ test ” command in the package.json file, SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses. Unit testing involves make examination causa for component and go them using Jest. Here are the high-level stairs: 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: 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 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: Now, let ’ s write a test for this component, mocking the axios module to control the datum that ’ s returned by the API: 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 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. 2. Run the tests: The tests can be run with the updated dictation: 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 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: 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: 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. 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 () 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. 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: Read More: Here are the advanced testing proficiency that can used for unit testing of React Apps using Jest: 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. In the first run, the output is save by Jest. Later, if the output modification, the examination will miscarry Read More: 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. This see if the part ’ s state (count) update aright when the button is clicked. Here are the benefits of unit testing React apps using Jest: Read More: Here are the best practices for testing React app with Jest: 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. Jest is chiefly used for unit testing, but it indorse integration examine and basic end-to-end testing too. You can use.skip modifieron a examination to skip unit test in Jest On This Page # Ask-and-Contributeabout this topic with our Discord community. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.Related Product
Unit Testing of React Apps using JEST: Tutorial
Overview
What is Unit Testing in React?
What is Unit testing React with Jest?
Why Unit Testing in React is significant?
What to test in Unit Testing for React Apps?
Prerequisite (Project Setup) of React Unit Testing in JEST
npm init vite @ latest jest-react-app -- template react
cd jest-react-app
npm install -- save-dev jest jest-axe
npx jest -- version
npm i axios
npm i –save-dev @ babel/preset-react @ babel/preset-env @ testing-library/jest-dom jest-environment-jsdom
module.exports = {presets: [[' @ babel/preset-env ', {targets: {node: 'current ',},},], ' @ babel/preset-react ', // Adds support for JSX], plugins: [],};module.exports = {testEnvironment: `` jsdom '', transform: {'^.+\\. (js|jsx|ts|tsx) $ ': 'babel-jest ',}, setupFilesAfterEnv: [' @ testing-library/jest-dom '],};`` scripts '': {//other scripts '' test '': `` jest ''},How to perform Unit prove of React Apps using JEST?
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 ();});Mocking Data in React Unit Testing with Jest
// 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;// 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 ();});Code Coverage during React Unit Testing using Jest
`` hand '': {'' test '': `` jest -- coverage '', // former scripts ...}npm run test
Performance Optimization in React Unit Testing
Accessibility Testing in React using Jest Axe
//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 ();});Common Challenges and Solutions of Testing React Apps with Jest
importee {waitFor} from ' @ testing-library/react ';jest.mock (' .. /api/fetchUser ');jest -u
Advanced Testing Techniques [With Example]
Snapshot examination:
// 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 ();});Testing Props and State
// 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 ');});Benefits of Unit Testing of React Apps using JEST
Best Practices for testing React Apps with JEST
Conclusion
Frequently Asked Questions
1. Is Jest for unit testing or integrating testing?
2. How do you 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
Related Guides
Automate This With SUSA
Test Your App Autonomously