| How to Test Forms in React :👈 | 👉:How to Test Custom Hooks |
How to Mock API Requests in React Tests |
How to Mock API Requests in React Tests
1. What Is API Mocking?
API mocking means replacing a real API request with a simulated response during testing.
For example, consider a React component that retrieves users from an API:
GET https://api.example.com/users
Normally, the application sends a request to the backend and receives user data.
During testing, we can mock the API and return sample data without contacting the actual server.
Why do we mock API requests?
- We don't need a running backend server.
- Tests execute faster and more reliably.
- We can simulate successful and failed API responses.
- We can test loading indicators.
- We can test different response data.
- We avoid depending on internet connectivity.
2. Different Ways to Mock API Requests
| Approach | Purpose | Best suited for |
|---|---|---|
| vi.fn() | Mocks a function that makes an API request. | Testing components with injected API functions. |
| vi.spyOn() | Replaces or observes an existing function. | Mocking global fetch or existing methods. |
| MSW | Intercepts HTTP requests and returns mock responses. | Realistic API integration testing. |
| Mocked Axios | Replaces Axios methods with mock functions. | Applications using Axios. |
3. Example: Create a React Component That Calls an API
Let's create a component that retrieves users from an API.
UserList.jsx
import { useEffect, useState } from 'react';
function UserList() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
useEffect(() => {
async function fetchUsers() {
try {
const response = await fetch(
'https://api.example.com/users'
);
if (!response.ok) {
throw new Error('Failed to fetch users');
}
const data = await response.json();
setUsers(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
fetchUsers();
}, []);
if (loading) {
return <p>Loading users...</p>;
}
if (error) {
return <p role="alert">{error}</p>;
}
return (
<div>
<h2>Users</h2>
<ul>
{users.map(user => (
<li key={user.id}>
{user.name}
</li>
))}
</ul>
</div>
);
}
export default UserList;
Our component has three possible states:
- Loading – The API request is in progress.
- Success – User information is displayed.
- Error – An error message is displayed.
4. Approach 1: Mock API Requests Using vi.spyOn()
This is a simple way to mock the browser's fetch function using Vitest.
We use vi.spyOn() to replace the global fetch function with a mock implementation.
Test successful API response
UserList.test.jsx
import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi, afterEach } from 'vitest';
import UserList from './UserList';
describe('UserList API tests', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('displays users returned by API', async () => {
const mockUsers = [
{ id: 1, name: 'John' },
{ id: 2, name: 'David' }
];
vi.spyOn(globalThis, 'fetch')
.mockResolvedValue({
ok: true,
json: async () => mockUsers
});
render(<UserList />);
expect(
await screen.findByText('John')
).toBeInTheDocument();
expect(
screen.getByText('David')
).toBeInTheDocument();
});
});
Explanation:
vi.spyOn(globalThis, 'fetch')creates a spy on the fetch function.mockResolvedValue()provides a successful Promise response.ok: truerepresents a successful HTTP response.json()returns the sample user data.findByText()waits for the user information to appear.
Test API failure
We should also test what happens when the backend returns an unsuccessful HTTP response.
it('displays an error when API request fails', async () => {
vi.spyOn(globalThis, 'fetch')
.mockResolvedValue({
ok: false,
status: 500,
json: async () => ({})
});
render(<UserList />);
expect(
await screen.findByRole('alert')
).toHaveTextContent('Failed to fetch users');
});
Here, fetch resolves successfully at the JavaScript Promise level, but the HTTP response has a failure status. This is why the component checks response.ok.
Test network failure
A network failure is different from an HTTP error. In this case, fetch rejects its Promise.
it('handles network errors', async () => {
vi.spyOn(globalThis, 'fetch')
.mockRejectedValue(new Error('Network error'));
render(<UserList />);
expect(
await screen.findByRole('alert')
).toHaveTextContent('Network error');
});
5. Test Loading State
Sometimes an API request takes time. We should verify that the loading message is displayed while the request is pending.
it('displays loading message while API is pending', async () => {
let resolveRequest;
const pendingRequest = new Promise(resolve => {
resolveRequest = resolve;
});
vi.spyOn(globalThis, 'fetch')
.mockReturnValue(pendingRequest);
render(<UserList />);
expect(
screen.getByText('Loading users...')
).toBeInTheDocument();
resolveRequest({
ok: true,
json: async () => [
{ id: 1, name: 'John' }
]
});
expect(
await screen.findByText('John')
).toBeInTheDocument();
});
This test verifies both the loading state and the successful response after the request completes.
6. Approach 2: Mock API Functions Using vi.fn()
Instead of calling fetch directly inside a component, we can separate API logic into another file.
This makes the application easier to maintain and test.
Create API service
userService.js
export async function getUsers() {
const response = await fetch(
'https://api.example.com/users'
);
if (!response.ok) {
throw new Error('Failed to fetch users');
}
return response.json();
}
Use the service in the component
UserList.jsx
import { useEffect, useState } from 'react';
import { getUsers } from './userService';
function UserList() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
useEffect(() => {
async function loadUsers() {
try {
const data = await getUsers();
setUsers(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
loadUsers();
}, []);
if (loading) return <p>Loading users...</p>;
if (error) {
return <p role="alert">{error}</p>;
}
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
export default UserList;
Mock the service function
UserList.test.jsx
import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import { getUsers } from './userService';
import UserList from './UserList';
vi.mock('./userService', () => ({
getUsers: vi.fn()
}));
describe('UserList', () => {
it('displays users from mocked service', async () => {
getUsers.mockResolvedValue([
{ id: 1, name: 'John' },
{ id: 2, name: 'David' }
]);
render(<UserList />);
expect(
await screen.findByText('John')
).toBeInTheDocument();
expect(
screen.getByText('David')
).toBeInTheDocument();
expect(getUsers).toHaveBeenCalledTimes(1);
});
});
Important methods:
vi.mock()– Mocks an entire module.vi.fn()– Creates a mock function.mockResolvedValue()– Simulates a successful asynchronous result.mockRejectedValue()– Simulates an asynchronous failure.toHaveBeenCalledTimes()– Checks how many times a function was called.
7. Approach 3: Mock API Requests Using MSW
MSW stands for Mock Service Worker.
Unlike directly mocking fetch or an API service function, MSW intercepts HTTP requests and returns predefined responses.
This means your component can make a normal API request without knowing that the response is mocked.
Install MSW
npm install -D msw
Create API request handlers
src/mocks/handlers.js
import { http, HttpResponse } from 'msw';
export const handlers = [
http.get(
'https://api.example.com/users',
() => {
return HttpResponse.json([
{ id: 1, name: 'John' },
{ id: 2, name: 'David' }
]);
}
)
];
Here:
http.get()intercepts GET requests.- The URL identifies which API request should be intercepted.
HttpResponse.json()returns sample JSON data.
Configure the MSW server
src/mocks/server.js
import { setupServer } from 'msw/node';
import { handlers } from './handlers';
export const server = setupServer(...handlers);
Configure test setup
Update src/test/setup.js:
import '@testing-library/jest-dom/vitest';
import { beforeAll, afterAll, afterEach } from 'vitest';
import { server } from '../mocks/server';
beforeAll(() => {
server.listen({
onUnhandledRequest: 'error'
});
});
afterEach(() => {
server.resetHandlers();
});
afterAll(() => {
server.close();
});
Write the test
import { render, screen } from '@testing-library/react';
import { describe, it, expect } from 'vitest';
import UserList from './UserList';
describe('UserList with MSW', () => {
it('loads users from mocked API', async () => {
render(<UserList />);
expect(
await screen.findByText('John')
).toBeInTheDocument();
expect(
screen.getByText('David')
).toBeInTheDocument();
});
});
Notice that we do not mock fetch directly. MSW intercepts the actual HTTP request made by the component.
Test API error using MSW
We can override a handler for a particular test.
import { http, HttpResponse } from 'msw';
import { server } from '../mocks/server';
it('displays an API error', async () => {
server.use(
http.get(
'https://api.example.com/users',
() => {
return HttpResponse.json(
{ message: 'Server error' },
{ status: 500 }
);
}
)
);
render(<UserList />);
expect(
await screen.findByRole('alert')
).toHaveTextContent('Failed to fetch users');
});
server.use() temporarily overrides the matching handler. The afterEach() setup resets these overrides so they do not affect other tests.
8. How to Mock POST API Requests
Many React applications send data to APIs using POST requests. For example, a login form may submit email and password.
Example API service
authService.js
export async function login(credentials) {
const response = await fetch(
'https://api.example.com/login',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(credentials)
}
);
if (!response.ok) {
throw new Error('Login failed');
}
return response.json();
}
Mock POST request using MSW
import { http, HttpResponse } from 'msw';
export const handlers = [
http.post(
'https://api.example.com/login',
async ({ request }) => {
const body = await request.json();
if (
body.email === 'john@example.com' &&
body.password === 'secret123'
) {
return HttpResponse.json({
token: 'mock-token',
user: {
id: 1,
name: 'John'
}
});
}
return HttpResponse.json(
{ message: 'Invalid credentials' },
{ status: 401 }
);
}
)
];
This allows us to test both successful login and invalid credentials without connecting to a real authentication server.
9. Mocking Axios Requests
If your React application uses Axios instead of fetch, you can mock Axios methods using Vitest.
Example API service:
import axios from 'axios';
export async function getUsers() {
const response = await axios.get(
'https://api.example.com/users'
);
return response.data;
}
Mock Axios in the test:
import { vi, it, expect } from 'vitest';
import axios from 'axios';
import { getUsers } from './userService';
vi.mock('axios');
it('returns users from Axios API', async () => {
const mockUsers = [
{ id: 1, name: 'John' }
];
axios.get.mockResolvedValue({
data: mockUsers
});
const result = await getUsers();
expect(result).toEqual(mockUsers);
expect(axios.get).toHaveBeenCalledWith(
'https://api.example.com/users'
);
});
10. vi.fn() vs vi.spyOn() vs MSW
| Feature | vi.fn() | vi.spyOn() | MSW |
|---|---|---|---|
| Purpose | Creates a mock function. | Spies on or replaces an existing method. | Intercepts HTTP requests. |
| Mocks HTTP layer? | No, not by itself. | Only if used to replace an HTTP method. | Yes. |
| Tests actual request handling? | Usually no. | Usually no. | Yes, at the network request boundary. |
| Best use | Mocking service functions. | Mocking fetch or observing existing methods. | API integration testing. |
11. Which Approach Should You Use?
- Use vi.fn(): When your component receives an API function as a prop or imports a service that you want to mock.
- Use vi.spyOn(): When you want to replace an existing method such as fetch.
- Use MSW: When you want to test components and API services together while intercepting HTTP requests.
- Use mocked Axios: When you want to isolate an Axios-based service function.
Recommended approach: MSW is particularly useful for integration tests because it allows your application to make normal HTTP requests while providing controlled responses.
12. Best Practices
- Do not depend on a real backend for ordinary component tests.
- Test successful API responses and failed requests.
- Test loading indicators and empty responses.
- Test HTTP errors such as 400, 401, 404, and 500 when relevant.
- Keep mock response data realistic and consistent with the API contract.
- Reset mocks and handlers between tests.
- Use MSW when testing multiple components that depend on the same API.
- Keep API service logic separate from UI components where practical.
- Test network failures separately from HTTP error responses.
- Avoid mocking more than necessary because excessive mocking can hide integration problems.
13. Common Mistakes
| Mistake | Correct approach |
|---|---|
| Mocking only successful responses. | Test API failures and network errors too. |
| Forgetting to restore spies. | Use vi.restoreAllMocks() after tests when appropriate. |
| Not resetting MSW handlers. | Call server.resetHandlers() after each test. |
| Using getByText() for asynchronous results. | Use findByText() when waiting for API data. |
| Mocking the wrong API URL. | Make sure the handler URL matches the actual request. |
| Testing only the service function. | Also test how the component displays API results. |
| Confusing HTTP errors with network errors. | Test unsuccessful HTTP responses and rejected Promises separately. |
14. Interview Questions and Answers
1. What is API mocking in React?
API mocking means simulating backend responses during testing instead of sending requests to a real server.
2. Why do we mock API requests?
To make tests faster, reliable, independent of backend availability, and capable of testing different API scenarios.
3. What is MSW?
MSW stands for Mock Service Worker. It intercepts network requests and returns predefined responses without requiring changes to the application's API calling code.
4. What is the difference between vi.fn() and vi.spyOn()?
vi.fn() creates a new mock function, whereas vi.spyOn() observes or replaces an existing object's method.
5. How do you mock a failed API request?
With Vitest, use mockRejectedValue() to simulate a network failure or mockResolvedValue() with ok: false to simulate an unsuccessful HTTP response.
6. How do you test loading states?
Keep the mocked Promise pending, render the component, verify that the loading indicator appears, and then resolve the Promise and verify the resulting UI.
7. Can MSW mock POST requests?
Yes. MSW supports GET, POST, PUT, PATCH, DELETE, and other HTTP methods through its request handlers.
8. Should we mock every API request?
No. Mocking is useful for component and integration tests. Some end-to-end tests should run against a real test backend or a controlled test environment.
15. Summary
Mocking API requests is an important skill when testing React applications. It allows developers to test different backend scenarios without depending on an actual server.
- vi.fn() – Creates mock functions.
- vi.spyOn() – Mocks or observes existing methods.
- MSW – Intercepts HTTP requests and returns mock responses.
- mockResolvedValue() – Simulates successful asynchronous results.
- mockRejectedValue() – Simulates rejected Promises.
- server.use() – Overrides MSW handlers for individual tests.
- server.resetHandlers() – Restores the initial request handlers.
Key takeaway: Use simple Vitest mocks for isolated service tests and consider MSW for realistic React integration tests that involve HTTP requests.
| How to Test Forms in React :👈 | 👉:How to Test Custom Hooks |
Comments and Discussion