| How to Test Custom Hooks :👈 | 👉:How to Test Components That Use Context |
How to Test Loading and Error States |
How to Test Loading and Error States in React
1. What Are Loading and Error States?
When a React application communicates with an API, the request does not complete immediately. The application must handle different situations.
For example, consider a user dashboard that retrieves information from a backend API.
The application may have the following states:
| State | Description | Example UI |
|---|---|---|
| Loading | API request is in progress. | Loading users... |
| Success | API returns valid data. | Display user information. |
| Error | API request fails. | Unable to load users. |
| Empty | API succeeds but returns no records. | No users found. |
2. Why Should We Test These States?
- Ensure users receive feedback while waiting for API responses.
- Verify that error messages appear when requests fail.
- Prevent blank screens during API failures.
- Verify that successful responses replace loading indicators.
- Ensure empty results are handled correctly.
- Verify retry functionality.
- Prevent incorrect UI behavior during asynchronous operations.
3. Tools Required
| Tool | Purpose |
|---|---|
| React Testing Library | Renders components and checks their UI. |
| user-event | Simulates user interactions. |
| Vitest | Runs test cases and provides mocking. |
| MSW | Intercepts API requests and returns mock responses. |
| jsdom | Provides a browser-like DOM environment. |
4. Create a React Component with Loading and Error States
Let's create a component that fetches user information 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('');
async function fetchUsers() {
setLoading(true);
setError('');
try {
const response = await fetch(
'https://api.example.com/users'
);
if (!response.ok) {
throw new Error('Failed to load users');
}
const data = await response.json();
setUsers(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
useEffect(() => {
fetchUsers();
}, []);
if (loading) {
return <p role="status">Loading users...</p>;
}
if (error) {
return (
<div>
<p role="alert">{error}</p>
<button onClick={fetchUsers}>
Retry
</button>
</div>
);
}
if (users.length === 0) {
return <p>No users found</p>;
}
return (
<div>
<h2>Users</h2>
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
export default UserList;
This component handles four different situations:
- Displays a loading message while fetching data.
- Displays users when the API succeeds.
- Displays an error message when the API fails.
- Displays an empty-state message when no users are returned.
5. Configure Vitest
Install the required packages if they are not already installed.
npm install -D vitest jsdom
npm install -D @testing-library/react
npm install -D @testing-library/user-event
npm install -D @testing-library/jest-dom
Update vite.config.js:
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
setupFiles: './src/test/setup.js'
}
});
Create src/test/setup.js:
import '@testing-library/jest-dom/vitest';
6. Test Loading State
We need to verify that the loading message appears while the API request is still pending.
To test this, we create a Promise that does not resolve immediately.
import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi, afterEach } from 'vitest';
import UserList from './UserList';
describe('UserList loading tests', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('displays loading message while API is pending', () => {
vi.spyOn(globalThis, 'fetch')
.mockReturnValue(new Promise(() => {}));
render(<UserList />);
expect(
screen.getByRole('status')
).toHaveTextContent('Loading users...');
});
});
Explanation:
vi.spyOn()replaces the fetch implementation with a mock.new Promise(() => {})creates a Promise that remains pending.render()renders the React component.getByRole('status')finds the loading message.
Because the API request never completes, the component remains in its loading state.
7. Test Successful API Response
Next, verify that the loading message disappears and user information appears after a successful API response.
it('displays users after successful API response', 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();
expect(
screen.queryByRole('status')
).not.toBeInTheDocument();
});
Important: findByText() waits for the API response and resulting UI update. queryByRole() is useful for checking that the loading message is no longer present.
8. Test API Error State
Sometimes the server returns an unsuccessful HTTP response, such as 500 Internal Server Error.
We should verify that the component displays the expected error message.
it('displays error message when API returns failure', async () => {
vi.spyOn(globalThis, 'fetch')
.mockResolvedValue({
ok: false,
status: 500
});
render(<UserList />);
expect(
await screen.findByRole('alert')
).toHaveTextContent('Failed to load users');
expect(
screen.getByRole('button', { name: /retry/i })
).toBeInTheDocument();
});
Here, fetch resolves with an HTTP error response. The component checks response.ok and throws an error, which is then displayed in the UI.
9. Test Network Failure
An HTTP error and a network error are different.
- HTTP error: The server responds with a status such as 500 or 404.
- Network error: The request cannot complete because of a network problem, and fetch rejects its Promise.
Test network failure:
it('displays error when network request fails', async () => {
vi.spyOn(globalThis, 'fetch')
.mockRejectedValue(new Error('Network error'));
render(<UserList />);
expect(
await screen.findByRole('alert')
).toHaveTextContent('Network error');
});
This verifies that the component handles rejected API requests correctly.
10. Test Empty State
Sometimes an API request succeeds but returns an empty array.
For example:
[
// No user records
]
The application should display a meaningful message instead of showing a blank list.
it('displays empty message when no users are returned', async () => {
vi.spyOn(globalThis, 'fetch')
.mockResolvedValue({
ok: true,
json: async () => []
});
render(<UserList />);
expect(
await screen.findByText('No users found')
).toBeInTheDocument();
});
This test verifies that an empty API response is handled as a valid result rather than an error.
11. Test Retry Functionality
A retry button allows users to try the API request again after a failure.
We should test both the initial failure and the successful retry.
import userEvent from '@testing-library/user-event';
it('retries API request successfully', async () => {
const user = userEvent.setup();
vi.spyOn(globalThis, 'fetch')
.mockResolvedValueOnce({
ok: false,
status: 500
})
.mockResolvedValueOnce({
ok: true,
json: async () => [
{ id: 1, name: 'John' }
]
});
render(<UserList />);
expect(
await screen.findByRole('alert')
).toHaveTextContent('Failed to load users');
await user.click(
screen.getByRole('button', { name: /retry/i })
);
expect(
await screen.findByText('John')
).toBeInTheDocument();
expect(fetch).toHaveBeenCalledTimes(2);
});
Explanation:
mockResolvedValueOnce()provides a response for one specific call.- The first request returns an HTTP error.
- The second request returns successful user data.
- The test clicks Retry and verifies that the user appears.
toHaveBeenCalledTimes(2)verifies that two requests were made.
12. Test Loading State During Retry
It is also important to verify that the loading indicator appears again when the user retries a failed request.
it('shows loading state while retrying', async () => {
const user = userEvent.setup();
let resolveRetry;
const retryPromise = new Promise(resolve => {
resolveRetry = resolve;
});
vi.spyOn(globalThis, 'fetch')
.mockResolvedValueOnce({
ok: false,
status: 500
})
.mockReturnValueOnce(retryPromise);
render(<UserList />);
expect(
await screen.findByRole('alert')
).toBeInTheDocument();
await user.click(
screen.getByRole('button', { name: /retry/i })
);
expect(
screen.getByRole('status')
).toHaveTextContent('Loading users...');
resolveRetry({
ok: true,
json: async () => [
{ id: 1, name: 'John' }
]
});
expect(
await screen.findByText('John')
).toBeInTheDocument();
});
This verifies that retrying follows the same loading and success behavior as the initial request.
13. Test Loading and Error States Using MSW
MSW (Mock Service Worker) intercepts HTTP requests and returns mock responses. It is useful when we want to test the component and its actual API request together.
Install MSW
npm install -D msw
Create 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' }
]);
}
)
];
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();
});
Test successful response
import { render, screen } from '@testing-library/react';
import { it, expect } from 'vitest';
import UserList from './UserList';
it('loads users using MSW', async () => {
render(<UserList />);
expect(
await screen.findByText('John')
).toBeInTheDocument();
});
Test error response
import { http, HttpResponse } from 'msw';
import { server } from '../mocks/server';
it('displays server error using MSW', 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 load users');
});
MSW allows us to change the API response for individual test cases without modifying the React component.
14. getBy, queryBy, and findBy for State Testing
Choosing the correct query is important when testing loading and error states.
| Query | Behavior | When to use |
|---|---|---|
| getByRole() | Finds an element immediately or throws an error. | Checking an element that should already exist. |
| queryByRole() | Returns null when an element is missing. | Checking that loading or error messages disappear. |
| findByRole() | Waits for an element to appear. | Checking asynchronous API results. |
Example:
// Loading message should exist immediately
expect(screen.getByRole('status')).toBeInTheDocument();
// Error message should appear asynchronously
expect(
await screen.findByRole('alert')
).toBeInTheDocument();
// Loading message should disappear
expect(
screen.queryByRole('status')
).not.toBeInTheDocument();
15. Common Testing Mistakes
| Mistake | Correct approach |
|---|---|
| Checking loading state after the API has completed. | Keep the mocked Promise pending. |
| Using getByText() for asynchronous messages. | Use findByText() or findByRole(). |
| Testing only successful responses. | Test HTTP errors and network failures too. |
| Ignoring empty API responses. | Test empty-state behavior separately. |
| Not testing retry functionality. | Simulate failure followed by success. |
| Confusing HTTP errors with rejected requests. | Test both response.ok = false and rejected Promises. |
| Not restoring mocked functions. | Use vi.restoreAllMocks() where appropriate. |
| Checking internal React state directly. | Check what the user can see on the screen. |
16. Best Practices
- Test loading, success, error, and empty states separately.
- Use role="status" for loading information and role="alert" for important error messages.
- Use realistic API responses in tests.
- Test network failures separately from HTTP failures.
- Test retry behavior when the application provides a retry option.
- Verify that loading indicators disappear after requests complete.
- Use MSW for realistic integration tests.
- Use Vitest mocks for simpler isolated tests.
- Ensure error messages are understandable to users.
- Test that the UI does not remain stuck in loading state after a failure.
- Test component behavior rather than implementation details.
17. Interview Questions and Answers
1. What are loading and error states in React?
Loading state indicates that an asynchronous operation is in progress. Error state indicates that the operation failed and the application needs to display an appropriate message.
2. How do you test a loading indicator?
Mock the API request with a Promise that remains pending, render the component, and verify that the loading indicator appears.
3. How do you test API failure?
Mock fetch with an unsuccessful HTTP response or a rejected Promise, then verify that the expected error message appears.
4. What is the difference between HTTP error and network error?
An HTTP error is a response returned by the server with an unsuccessful status code. A network error occurs when the request itself fails and the Promise rejects.
5. What is the purpose of findByRole()?
It waits for an element to appear asynchronously and returns a Promise containing the matching element.
6. Why do we use queryByRole()?
It returns null when an element does not exist, making it useful for checking that a loading indicator or error message has disappeared.
7. How do you test retry functionality?
Mock the first API request to fail and the next request to succeed. Click the Retry button and verify that the successful response is displayed.
8. What is MSW?
MSW stands for Mock Service Worker. It intercepts HTTP requests and returns controlled responses during testing.
9. Why should we test empty states?
An API can succeed without returning records. Testing empty states ensures that users see a meaningful message instead of an unexplained blank screen.
10. Should loading and error states be tested separately?
Yes. Each state represents different application behavior and should have focused test cases. We should also test transitions between these states.
18. Summary
Testing loading and error states is essential for building reliable React applications that communicate with APIs.
Important concepts to remember:
- Loading state: Displays feedback while an API request is pending.
- Success state: Displays the data returned by the API.
- Error state: Displays a meaningful message when a request fails.
- Empty state: Handles successful responses with no records.
- findByRole(): Waits for asynchronous UI elements.
- queryByRole(): Checks whether an element is absent.
- mockResolvedValueOnce(): Simulates a particular API response.
- mockRejectedValue(): Simulates a rejected Promise.
- MSW: Intercepts HTTP requests and provides controlled responses.
Key takeaway: A good React test suite should verify not only whether an API returns the correct data, but also how the application behaves while waiting, when something goes wrong, and when no data is available.
| How to Test Custom Hooks :👈 | 👉:How to Test Components That Use Context |
Comments and Discussion