How to Test React Components using Jest ?
Last Updated :
09 Jul, 2024
React is a frontend open-source JavaScript library, used to build interactive User Interfaces. React is focused on Single Page applications and is more popularly known as a SPA.Â
Testing is an important aspect of development. It examines whether the application is behaving as intended, and protects it when any unwanted changes are made to the application. There are various test libraries such as chai, mocha etc. In this tutorial, we'll be using the jest library along with reacting testing library to test out the React Components.
Prerequisites:
Modules required:
Creating React App and Setting Up:Â
Step 1: You will start a new project using create-react-app so open your terminal and type.
npx create-react-app jest-testing
Step 2: Switch to the jest-testing folder using the following command.
cd jest-testing
Step 3: Change to the src folder and remove the unnecessary stuff using the following command
cd src
rm*
Step 4: Create a components folder in the src folder
mkdir components
Step 5: Create a components folder in the src folder
cd components
Step 6: Create a Button folder and a Text folder
mkdir Button,Text
Step 7: Create a Button.js file and Button.test.js file inside the Button folder.
touch Button.js Button.test.js
Note: The name of the test file should be the same as the component and should be followed with a .test.js extension as when the tests are run using the npm test command, React automatically checks for all the file names with a .test extension and runs the tests.
Step 8: Create a Text.js file and Text.test.js file inside the Text folder.
touch Text.js Text.test.js
Step 9: In the src folder, create App.js, index.js, and App.test.js files.
touch App.js index.js App.test.js
Project Structure: The file structure in the project will look like this.
Project StructureExample: Setup all the files with basic code to toggle the text GeeksForGeeks when a button is clicked.
index.js
JavaScript
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
Button.js
JavaScript
const Button = ({ setToggle, btnTxt }) => {
// data-testid is a testing id
// which is used only during tests
return <button data-testid="button"
onClick={() => setToggle((prev) => !prev)}>
{btnTxt}
</button>
}
export default Button;
Text.js
JavaScript
const Text = ({ toggle, displayTxt }) => {
// data-testid is a testing id
// which is used only during tests
return <h1 data-testid="text">{toggle ? displayTxt : ""}</h1>
}
export default Text;
App.js
JavaScript
import Button from "./components/Button/Button";
import Text from "./components/Text/Text";
import { useState } from "react";
const App = () => {
const [toggle, setToggle] = useState(true);
return (
<div className="App">
<Text toggle={toggle} displayTxt="GeeksForGeeks" />
<Button setToggle={setToggle} btnTxt="Toggle Text" />
</div>
);
}
export default App;
Output: Run the following command to start up the application:
npm start
A simple app is created which toggles the text GeeksForGeeks when the button is pressed.

Now that the basic application is set up, we can begin testing it. Before testing the application let's learn about a few important testing methods.
- render(Component): Renders the given component on a mock screen.
- screen: A reference to the mock screen with various useful testing functions.
- cleanup(): Resets the DOM.
- afterEach(callback function): Runs the callback function given as a parameter after running each test suite.
- beforeEach(callback function): Runs the callback function given as a parameter before running each test suite.
- describe(nameOfTestSuite, callback function): Defines a test suite that contains many unit tests(Callback Function contains the unit tests).
- test(nameOfTest, callback function): Defines a test to be performed.
- fireEvent: Simulates a specified event.
Testing the Button Component: We are going to perform two tests on the Button Component.Â
- Test 1: Testing if the button is rendered correctly to the DOM.
- Test 2: Testing if the button displays the text passed as a prop.
Button.test.js
JavaScript
import { render, screen, cleanup } from "@testing-library/react";
// Importing the jest testing library
import '@testing-library/jest-dom'
import Button from "./Button";
// afterEach function runs after each test suite is executed
afterEach(() => {
cleanup(); // Resets the DOM after each test suite
})
describe("Button Component", () => {
const setToggle = jest.fn();
render(<Button setToggle={setToggle} btnTxt="Click Me!" />);
const button = screen.getByTestId("button");
// Test 1
test("Button Rendering", () => {
expect(button).toBeInTheDocument();
})
// Test 2
test("Button Text", () => {
expect(button).toHaveTextContent("Click Me!");
})
})
Output:
Run the tests using the following command:
npm test
Test ResultWe can see that two test suites have failed and one has passed. The reason for this is that no tests have been designed for the Text Component and the App Component. So the only test suite passing is the Button Component.
Testing the Text Component: We are going to perform three tests on the Text Component.
- Test 1: Testing if the text element is rendered correctly to the DOM.
- Test 2: Testing the content of the text element when the toggle is set to true.
- Test 3: Testing the content of the text element when the toggle is set to false.
Text.test.js
JavaScript
import { render, screen, cleanup } from "@testing-library/react";
// Importing the jest testing library
import '@testing-library/jest-dom'
import Text from "./Text";
// afterEach function runs after each test suite is executed
afterEach(() => {
cleanup();
})
describe("Text Component", () => {
// Test 1
test("Text Rendering", () => {
render(<Text toggle={true} displayTxt={"GeeksForGeeks"} />);
const text = screen.getByTestId("text");
expect(text).toBeInTheDocument();
})
// Test 2
test("Displayed Text when toggle is set to true", () => {
render(<Text toggle={true} displayTxt={"GeeksForGeeks"} />)
const text = screen.getByTestId("text");
expect(text).toHaveTextContent("GeeksForGeeks");
})
// Test 3
test("Displayed Text when toggle is set to false", () => {
render(<Text toggle={false} displayTxt={"GeeksForGeeks"} />);
const text = screen.getByTestId("text");
expect(text).toBeEmptyDOMElement();
})
})
Output:
Run the tests using the following command:
npm test
Test ResultTesting the App Component: Testing the App Component is also known as integration testing as we the testing the application when we have integrated our button and text components. We are going to perform three tests on the App Component.
- Test 1: Testing whether all the components have rendered
- Test 2: Testing the default value of the text element
- Test 3: Testing the toggle ability of the button
App.js
JavaScript
import { render, screen, cleanup, fireEvent } from "@testing-library/react";
// Importing the jest testing library
import '@testing-library/jest-dom'
import App from "./App";
// afterEach function runs after each test suite is executed
afterEach(() => {
cleanup();
})
describe("App Component", () => {
// Test 1
test("App Rendering", () => {
render(<App />); // Rendering the App
const text = screen.getByTestId("text");
const button = screen.getByTestId("button");
expect(button).toBeInTheDocument();
expect(text).toBeInTheDocument();
})
// Test 2
test("Default Text", () => {
render(<App />);
const text = screen.getByTestId("text");
expect(text).toHaveTextContent("GeeksForGeeks");
})
// Test 3
test("Toggling Text", () => {
render(<App />);
const text = screen.getByTestId("text");
const button = screen.getByTestId("button");
expect(text).toHaveTextContent("GeeksForGeeks");
fireEvent.click(button);
expect(text).toBeEmptyDOMElement();
fireEvent.click(button);
expect(text).toHaveTextContent("GeeksForGeeks");
})
})
Output: Run the tests using the following command:
npm test
Test Result
Similar Reads
How to write unit tests for React components?
A React component is a small, reusable piece of code that represents a part of a user interface in a web application. Components can contain their own data, logic, and visual elements, making it easy to build complex user interfaces by combining and nesting them together. To write unit tests for Rea
2 min read
How to use Paper Component in ReactJS ?
In Material Design, the physical properties of paper are translated to the screen. Material UI for React has this component available for us and it is very easy to integrate. We can use the Paper Component in ReactJS using the following approach. Prerequisites:React JSMaterial UIApproachTo use Paper
2 min read
How to use Portal Component in ReactJS ?
The portal component renders its children into a new subtree outside the current DOM hierarchy. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Portal Component in ReactJS using the following approach.Prerequisites:NodeJS or NPMReact JSMate
2 min read
How to Integrate Redux with React Components ?
Redux is an open-source JavaScript library for managing and centralizing application state. It helps you to write applications that behave consistently and are easy to test and run in different environments. It can also be understood as the predictable state container for the JavaScript app. It is m
4 min read
How to Pass JSON Values into React Components ?
In React, you can pass JSON values into components using props. Props allow us to send data from a parent component to its child components. When rendering a component, you can pass the JSON values as props. These props can then be accessed within the componentâs function or class, allowing you to d
3 min read
How to create components in ReactJS ?
Components in React JS is are the core of building React applications. Components are the building blocks that contains UI elements and logic, making the development process easier and reusable. In this article we will see how we can create components in React JS. Table of Content React Functional C
3 min read
How to use React Context with React-Redux ?
React context with React-Redux is a popular state management library for React applications. Using React context with React-Redux is a powerful way to provide the Redux store to components deep within your component tree without manually passing it down through props. PrerequisitesNode.js and NPMRea
3 min read
How to connect the components using Connect() in React Redux
In React Redux, you use the connect() function to connect your components to the Redux store. This function takes two parameters: mapStateToProps and mapDispatchToProps. mapStateToProps maps the store's state to the component's props, while mapDispatchToProps maps dispatch actions to props. By using
3 min read
How to test CSS property of an element using Protractor ?
Protractor is an end-to-end test framework developed for Angular and AngularJS applications. It run tests against the application interacting with it as a real user would, running in a real browser. In this article, we are going to test the CSS property of an element. Pre-requisite: Installation and
3 min read
How to update the State of a component in ReactJS ?
To display the latest or updated information, and content on the UI after any User interaction or data fetch from the API, we have to update the state of the component. This change in the state makes the UI re-render with the updated content. Prerequisites: NPM & Node.jsReact JSReact StateReact
3 min read