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
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
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
Useful Testing Tools, Libraries and Frameworks For React Developers We all know the love of developers for the most popular library, React. It's easy to learn, and it's easy to build the user interface of any website using React. If you're building an application, no matter what, you should test your application before serving it to the user. If you are a front-end
7 min read
How to Start Unit Testing to a JavaScript Code? Unit testing is a crucial part of software development that helps ensure individual parts of the code work correctly. For JavaScript, unit testing can be especially valuable given the dynamic nature of the language. This guide will introduce you to the two popular approaches to unit testing in JavaS
3 min read
How to Test React Components using Jest ? 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 i
6 min read
How to Test TypeScript with Jest? Jest, a powerful JavaScript testing framework, seamlessly integrates with TypeScript, providing all the tools needed to write and run tests for your TypeScript code, ensuring quality and reliability. It handles TypeScript compilation automatically, offers features like mocking and code coverage, and
3 min read
Building a Component Library with React Hooks and Storybook Building a component library is a powerful way to streamline the development process, ensure consistency across projects, and promote the reusability of UI elements. In this article, we'll explore how to create a component library using React Hooks and Storybook, a tool for developing UI components
3 min read