How to Test Axios in React
Testing Axios in React applications ensures that your components correctly handle API requests and render data without making actual network calls. This article provides a straightforward guide on how to mock the Axios library using Jest and React Testing Library, allowing you to simulate both successful API responses and network errors in your test environment.
Why Mock Axios?
When writing unit tests for React components, you should avoid making real HTTP requests. Real network requests make tests slow, fragile, and dependent on external server availability. By mocking Axios, you control the API’s response data and status codes, allowing you to test how your UI behaves under various conditions.
Setting Up the React Component
Consider a simple UserList component that fetches users
from an API when it mounts and displays them in a list.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function UserList() {
const [users, setUsers] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/users')
.then(response => setUsers(response.data))
.catch(err => setError('Failed to fetch users'));
}, []);
if (error) return <div>{error}</div>;
return (
<ul>
{users.map(user => (
<li key={user.id} data-testid="user-item">{user.name}</li>
))}
</ul>
);
}
export default UserList;Testing Axios with Jest Mocking
The most common way to test Axios in React is by using
jest.mock('axios'). This replaces the actual Axios module
with a mock version that you can configure to return specific data.
Here is the test file using Jest and React Testing Library:
import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import axios from 'axios';
import UserList from './UserList';
// Mock the axios module
jest.mock('axios');
describe('UserList Component', () => {
afterEach(() => {
jest.clearAllMocks();
});
test('renders user list on successful API call', async () => {
const dummyUsers = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Doe' },
];
// Mock axios.get to resolve with fake data
axios.get.mockResolvedValueOnce({ data: dummyUsers });
render(<UserList />);
// Assert that the items eventually render in the document
const userItems = await waitFor(() => screen.getAllByTestId('user-item'));
expect(userItems).toHaveLength(2);
expect(userItems[0]).toHaveTextContent('John Doe');
expect(userItems[1]).toHaveTextContent('Jane Doe');
// Verify the correct API URL was called
expect(axios.get).toHaveBeenCalledWith('https://jsonplaceholder.typicode.com/users');
});
test('renders error message on API failure', async () => {
// Mock axios.get to reject with an error
axios.get.mockRejectedValueOnce(new Error('Network Error'));
render(<UserList />);
const errorMessage = await screen.findByText('Failed to fetch users');
expect(errorMessage).toBeInTheDocument();
});
});Key Takeaways for Testing Axios
jest.mock('axios'): Place this at the top of your test file to automatically mock all Axios methods.axios.get.mockResolvedValueOnce(): Use this to simulate a successful API response. You must match the structure of the Axios response object (e.g., nesting your mock data inside adataproperty).axios.get.mockRejectedValueOnce(): Use this to simulate network or server errors to test your error-handling UI.waitFororfindBy: Because API calls are asynchronous, use async query utilities from React Testing Library to wait for the UI to update.