React30-Part 26: Mocking data in API calls using react-testing-library
Mocking data and dependencies is a crucial aspect of testing frontend applications. It allows you to simulate various scenarios and ensure your components handle different situations gracefully. In this step, we’ll cover how to mock API calls. Let’s explore these concepts with examples using actual component code.
Mocking API Calls
Testing components that interact with APIs is essential to verify their behavior under different data conditions.
Example Component: UserListComponent
// UserListComponent.jsx
import React, { useState, useEffect, lazy } from "react";
const UserListComponent = () => {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((data) => setUsers(data));
}, []);
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
};
export default UserListComponent;
Writing the Test:
// UserListComponent.test.jsx
import React from "react";
import { render, screen, waitFor } from "@testing-library/react";
import UserListComponent from "./UserListComponent";
beforeEach(() => {
jest.spyOn(global, "fetch").mockResolvedValue({
json: jest.fn().mockResolvedValue([
{ id: 1, name: "John Doe" },
{ id: 2, name: "Jane Doe" }
])
});
});
test("displays a list of users", async () => {
// Render the component
setTimeout(async () => {
render(<UserListComponent />);
// Wait for API call to resolve
await waitFor(() => {
expect(screen.getByText(/John Doe/i)).toBeInTheDocument();
expect(screen.getByText(/Jane Doe/i)).toBeInTheDocument();
});
}, 1000);
});
In this example, the UserListComponent
fetches a list of users from an API. We mock the fetch
function to return a predefined list of users. The test then verifies that the component correctly displays the users. We are using setTimeout to allow jest.spyOn code to execute and mock fetch call before component is rendered by render method.
Codesandbox link:-
CodeSandbox
Conclusion
These example demonstrates how to mock data in React components using Jest and React Testing Library. By simulating different scenarios, you can ensure that your components handle various situations effectively. This level of testing is crucial for building robust and reliable frontend applications, especially when dealing with external data sources and global state management. Have a nice day ahead!
Check out my Youtube channel for more content:-
SaurabhNative-Youtube