How To Test React App With Jest and React Testing Library?
Last Updated :
30 Sep, 2024
Jest is a JavaScript testing framework maintained by Facebook, designed with a focus on simplicity and support for large JavaScript applications, especially React. It offers built-in utilities like test runners, mocking, snapshot testing, and code coverage reporting.
React Testing Library (RTL) is a lightweight solution for testing React components. Unlike traditional testing libraries like Enzyme, RTL promotes testing components in a way that closely resembles how users interact with them. Instead of focusing on testing the internal implementation, RTL emphasizes testing the UI behaviour and user interactions.
Key Features:
- Jest: Provides test runners, mocking, snapshot testing, and more.
- RTL: Focuses on how your components are used by simulating real user interactions (e.g., clicks, inputs).
By combining Jest and RTL, you can write powerful, user-centric tests that validate the actual behaviour of your React components.
Steps To Test React Application
Step 1: Create a New React App
Open your terminal and run the following command to create a new React app:
npx create-react-app react-testing-example
Navigate into the project directory:
cd react-testing-example
Step 2: Install React Testing Library Dependencies
npm install @testing-library/react @testing-library/jest-dom --save-dev
Folder Structure
Folder StructureDependencies
"dependencies": {
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
"devDependencies": {
"@testing-library/jest-dom": "^6.5.0",
"@testing-library/react": "^16.0.1"
}
Step 3: Create and Test Components
1. Create Button.js and Button.test.js Component
JavaScript
// src/components/Button.js
import React from 'react';
function Button({ label, onClick }) {
return <button onClick={onClick}>{label}</button>;
}
export default Button;
JavaScript
// src/components/Button.test.js
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import Button from './Button';
test('renders button with correct label', () => {
render(<Button label="Click Me" />);
const buttonElement = screen.getByText(/click me/i);
expect(buttonElement).toBeInTheDocument();
});
test('calls onClick handler when button is clicked', () => {
const handleClick = jest.fn(); // Mock function
render(<Button label="Click Me" onClick={handleClick} />);
const buttonElement = screen.getByText(/click me/i);
fireEvent.click(buttonElement);
expect(handleClick).toHaveBeenCalledTimes(1);
});
2. Create FetchButton.js and FetchButton.test.js Component
JavaScript
// src/components/FetchButton.js
import React, { useState } from 'react';
function FetchButton({ fetchData }) {
const [data, setData] = useState(null);
const handleClick = async () => {
const result = await fetchData();
setData(result);
};
return (
<div>
<button onClick={handleClick}>Fetch Data</button>
{data && <p>{data}</p>}
</div>
);
}
export default FetchButton;
JavaScript
// src/components/FetchButton.test.js
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import FetchButton from './FetchButton';
test('fetches and displays data when button is clicked', async () => {
const mockFetchData = jest.fn().mockResolvedValue('Hello, World!');
render(<FetchButton fetchData={mockFetchData} />);
fireEvent.click(screen.getByText(/fetch data/i));
const dataElement = await screen.findByText(/hello, world!/i);
expect(dataElement).toBeInTheDocument();
expect(mockFetchData).toHaveBeenCalledTimes(1);
});
3. Modify App.js and App.test.js
JavaScript
// src/App.js
import React from 'react';
import Button from './components/Button';
import FetchButton from './components/FetchButton';
import './App.css';
function App() {
// Mock fetchData function for FetchButton
const mockFetchData = async () => {
return "Hello, World!";
};
return (
<div className="App">
<header className="App-header">
<h1>Testing React Components</h1>
{/* Button Component */}
<Button label="Click Me" onClick={() => alert("Button Clicked!")} />
{/* FetchButton Component */}
<FetchButton fetchData={mockFetchData} />
</header>
</div>
);
}
export default App;
JavaScript
// src/App.test.js
import React from "react";
import { render, screen } from "@testing-library/react";
import App from "./App";
test("renders the main heading", () => {
render(<App />);
const headingElement = screen.getByText(/Testing React Components/i);
expect(headingElement).toBeInTheDocument();
});
test('renders the button with label "Click Me"', () => {
render(<App />);
const buttonElement = screen.getByText(/Click Me/i);
expect(buttonElement).toBeInTheDocument();
});
test('renders the fetch button with label "Fetch Data"', () => {
render(<App />);
const fetchButtonElement = screen.getByText(/Fetch Data/i);
expect(fetchButtonElement).toBeInTheDocument();
});
To test the application run the following command.
npm test
Output
Test a React App with Jest and React Testing Library
Similar Reads
Testing Custom Hooks with React Testing Library
React hooks fall into two categories: built-in hooks provided by React itself and custom hooks, which are user-defined functions. The most commonly used built-in hooks are useState, useEffect, useMemo, and useCallback. Custom hooks in React are JavaScript functions that allow you to excerpt and reus
5 min read
Compare React Testing Library and Enzyme for Testing React Components.
React Testing Library and Enzyme are widely used testing utilities for React components. Although they serve the same purpose, their approaches and features differ. React Testing LibraryReact Testing Library is a lightweight testing utility for React. It emphasizes testing components from the user's
4 min read
When to Choose Enzyme Over React Testing Library?
When it comes to testing React components, developers often face the dilemma of choosing between Enzyme and React Testing Library (RTL). Both libraries serve the purpose of testing React components, but they have different philosophies and approaches. In this article, we'll explore the scenarios in
4 min read
How to import from React-Select CDN with React and Babel ?
In ReactJS, import from React-Select CDN is not done in a simple way as we do with the npm packages. To use them we need to use directly them in the HTML file. It does not work with the project set-up by creating a react app. Prerequisites:React JSHTML, CSS, JavaScriptSteps to Import React-Select CD
2 min read
What are queries in React Testing Library ?
In this article, we explain the concept of queries in the React Testing Library. Ensuring that components behave as expected when developing applications with React is crucial. One powerful tool for testing React components is the React Testing Library. At the heart of the React Testing Library lies
3 min read
How to set a Background Image With React Inline Styles ?
Setting a background image with React inline style is a straightforward method of using the images as background to enhance the UI of the wen application. How to Set Background Image in React ?To set background image with react inline styles we will be using the style attribute. This style attribute
2 min read
7 Common Testing Libraries/Frameworks used with React-Redux
Testing is a critical aspect of software development, ensuring that applications behave as expected and meet quality standards. In React-Redux applications, where state management plays a crucial role, effective testing becomes even more important. Fortunately, there are several testing libraries an
4 min read
What are the advantages of using create-react-app CLI ?
Introduction: To get started with any framework you need to understand what all files you need to install. With React you don't need to worry about this. React will install all the files required for you to get started with a single command. It will have all the necessary packages installed and you
3 min read
How to import recharts.js library to ReactJS file ?
Recharts.js is a redefined chart library built with React and D3. It helps in creating interactive line graphs, bar graphs, pie graphs, etc. One of the main principles of it is that all its components are independent, lightweight, and can be deployed easily. Prerequisites:NPM & Node.jsReact JSSt
2 min read
Create a Real-Time Weather Forecast App with React
Real-time weather forecast app with React involves integrating with a weather API to fetch weather data and display it in the UI. Individuals can use the app to check the current weather conditions, temperature, humidity, and other relevant weather data for their location or any city they are intere
5 min read