Testing Loading and Error States in React
Testing loading and error states in React is an important part of building reliable, responsive, and user-friendly web applications. When a React application fetches data from an API, submits a form, or performs an asynchronous operation, users may see a loading indicator while waiting or an error message if something goes wrong. Testing these states ensures that the application responds correctly to success, failure, and delays.
Course: JustAcademy React JS Training Course
Course Demo: Register for React JS Course Demo
1. Introduction to Loading and Error States
React applications frequently perform asynchronous tasks, such as retrieving user information, loading product lists, submitting forms, or communicating with a server. These operations may take time or fail because of network problems, invalid requests, server errors, or unexpected responses.
Loading and error states communicate the current status of an operation to the user.
- Loading state: Indicates that an operation is in progress.
- Success state: Displays the requested data or confirms that an operation completed successfully.
- Error state: Informs the user that an operation could not be completed.
- Empty state: Indicates that the operation succeeded but returned no results.
- Retry state: Allows users to attempt the failed operation again.
2. What Is a Loading State?
A loading state is a temporary interface displayed while an asynchronous operation is running. It prevents users from thinking that the application has frozen or failed to respond.
Examples of Loading States
- Displaying "Loading users..." while retrieving user records.
- Showing a spinner while fetching product information.
- Displaying skeleton placeholders while a page loads.
- Showing "Submitting..." while a form is being processed.
- Disabling a submit button to prevent duplicate requests.
Example of a Loading State
import { useEffect, useState } from 'react';
function UserProfile() {
const [loading, setLoading] = useState(true);
const [user, setUser] = useState(null);
useEffect(() => {
async function loadUser() {
try {
const response = await fetch('/api/user');
if (!response.ok) {
throw new Error('Failed to load user');
}
const data = await response.json();
setUser(data);
} finally {
setLoading(false);
}
}
loadUser();
}, []);
if (loading) {
return <p role="status">Loading user...</p>;
}
if (!user) {
return <p>No user information available.</p>;
}
return <h2>{user.name}</h2>;
}
export default UserProfile;
This example demonstrates a loading indicator and a successful data display. In a production component, errors should also be caught and represented explicitly rather than allowing a rejected request to become an unhandled error.
3. What Is an Error State?
An error state is displayed when an operation cannot be completed successfully. A well-designed error state explains the problem in understandable language and, when appropriate, provides a way to recover.
Common Causes of Errors
- Internet connectivity problems.
- Server errors, such as HTTP 500 responses.
- Unauthorized or forbidden requests.
- Invalid request parameters.
- Malformed or unexpected API responses.
- Unexpected exceptions in application logic.
Example of an Error State
import { useEffect, useState } from 'react';
function ProductList() {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
useEffect(() => {
async function loadProducts() {
try {
const response = await fetch('/api/products');
if (!response.ok) {
throw new Error('Unable to load products');
}
const data = await response.json();
setProducts(data);
} catch {
setError('Unable to load products. Please try again.');
} finally {
setLoading(false);
}
}
loadProducts();
}, []);
if (loading) {
return <p role="status">Loading products...</p>;
}
if (error) {
return <p role="alert">{error}</p>;
}
if (products.length === 0) {
return <p>No products found.</p>;
}
return (
<ul>
{products.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
}
export default ProductList;
The component distinguishes loading, error, empty, and success states. Notice that fetch() does not automatically reject its promise for HTTP error responses, so checking response.ok is important.
4. Why Test Loading and Error States?
Testing these states helps verify that the application remains understandable and usable when network operations take time or fail.
- Confirms that a loading indicator appears at the correct time.
- Ensures loading indicators disappear after an operation completes.
- Verifies that server failures display useful messages.
- Checks that successful data is displayed correctly.
- Prevents failed requests from producing misleading success messages.
- Ensures retry actions work as expected.
- Checks that buttons are disabled or enabled appropriately.
- Helps identify unhandled promise rejections and unexpected UI behaviour.
5. Tools for Testing Loading and Error States
5.1 React Testing Library
React Testing Library helps test components through their rendered interface. Tests can check visible loading messages, error alerts, retry buttons, and successfully loaded content.
5.2 user-event
The @testing-library/user-event package simulates user interactions, such as clicking a retry button or submitting a form.
5.3 Vitest
Vitest provides test execution, assertions, and mock functions. It is commonly used with React applications built using Vite.
5.4 Jest
Jest is another testing framework used for React projects. Choose the test runner that matches your project configuration.
5.5 jest-dom Matchers
The @testing-library/jest-dom package provides useful DOM assertions, including toBeInTheDocument(), toHaveTextContent(), and toBeDisabled().
6. Setting Up the Testing Environment
For a Vite-based React project using Vitest, install the following development dependencies:
npm install -D vitest jsdom @testing-library/react @testing-library/user-event @testing-library/jest-dom
Configure Vitest to use a simulated browser environment.
// 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'
}
});
Load the Vitest-compatible DOM matchers in the setup file.
// src/test/setup.js
import '@testing-library/jest-dom/vitest';
Add a test script to package.json if needed:
{
"scripts": {
"test": "vitest",
"test:run": "vitest run"
}
}
These setup instructions are for Vitest. If the project uses Jest, configure the equivalent test environment and matchers for Jest instead.
7. Creating a Component with Loading, Error, and Success States
Consider a React component that loads a list of users from an API. It should display a loading message during the request, an error message if the request fails, and user information when the request succeeds.
// Users.jsx
import { useEffect, useState } from 'react';
export default function Users() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
async function loadUsers() {
setLoading(true);
setError('');
try {
const response = await fetch('/api/users');
if (!response.ok) {
throw new Error('Request failed');
}
const data = await response.json();
setUsers(data);
} catch {
setError('Unable to load users');
} finally {
setLoading(false);
}
}
useEffect(() => {
loadUsers();
}, []);
if (loading) {
return <p role="status">Loading users...</p>;
}
if (error) {
return (
<div>
<p role="alert">{error}</p>
<button onClick={loadUsers}>Retry</button>
</div>
);
}
if (users.length === 0) {
return <p>No users found.</p>;
}
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
This component uses three main states: loading, error, and success. It also handles an empty list and provides a retry button when the request fails.
Implementation note: In a production application, consider preventing repeated requests while one is already in progress, handling component unmounts or stale requests, and ensuring the retry action cannot create conflicting requests.
8. Testing the Initial Loading State
The first test verifies that the loading indicator appears while the API request is still pending. A deferred promise allows the test to control when the request finishes.
import { render, screen } from '@testing-library/react';
import { expect, it, vi } from 'vitest';
import Users from './Users';
it('shows a loading message while the request is pending', () => {
vi.stubGlobal(
'fetch',
vi.fn(() => new Promise(() => {}))
);
render(<Users />);
expect(screen.getByRole('status')).toHaveTextContent(
/loading users/i
);
});
The mocked fetch promise never resolves in this example, so it is useful only for checking the initial loading state. Always restore global mocks after a test suite, and avoid leaving unresolved operations when they are not needed.
9. Testing the Successful Loading State
A successful loading test verifies that the loading indicator is eventually replaced by the returned data.
import { render, screen } from '@testing-library/react';
import { expect, it, vi } from 'vitest';
import Users from './Users';
it('displays users after a successful request', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: true,
json: async () => [
{ id: 1, name: 'Aarav' },
{ id: 2, name: 'Priya' }
]
})
);
render(<Users />);
expect(screen.getByRole('status')).toHaveTextContent(
/loading users/i
);
expect(await screen.findByText('Aarav')).toBeInTheDocument();
expect(screen.getByText('Priya')).toBeInTheDocument();
expect(screen.queryByRole('status')).not.toBeInTheDocument();
});
The findByText() query waits for the requested element to appear. The queryByRole() query is useful for checking that the loading indicator has disappeared. Testing Library documents these query patterns for asynchronous UI changes.
10. Testing an API Error Response
An API error test checks whether the component displays the expected error message when the server responds with a failed HTTP status.
it('displays an error when the API request fails', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: false,
status: 500,
json: async () => ({})
})
);
render(<Users />);
expect(await screen.findByRole('alert')).toHaveTextContent(
/unable to load users/i
);
expect(screen.getByRole('button', { name: /retry/i }))
.toBeInTheDocument();
});
This test simulates an HTTP 500 response. The component detects that the response is not successful, throws an error, and displays its user-friendly error state.
11. Testing Network Failures
A network failure can occur when the fetch request itself rejects, for example because the server is unreachable or the connection is interrupted. This differs from an HTTP error response, which returns a response object with a status code.
it('shows an error when the network request rejects', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockRejectedValue(new Error('Network unavailable'))
);
render(<Users />);
expect(await screen.findByRole('alert')).toHaveTextContent(
/unable to load users/i
);
});
Testing both rejected requests and unsuccessful HTTP responses helps cover different failure scenarios.
12. Testing the Retry Button
Retry testing verifies that a user can attempt the request again after an error. A useful test simulates a failed first request followed by a successful second request.
import userEvent from '@testing-library/user-event';
it('retries a failed request and displays users', async () => {
const user = userEvent.setup();
const fetchMock = vi.fn()
.mockResolvedValueOnce({
ok: false,
status: 500,
json: async () => ({})
})
.mockResolvedValueOnce({
ok: true,
json: async () => [{ id: 1, name: 'Aarav' }]
});
vi.stubGlobal('fetch', fetchMock);
render(<Users />);
expect(await screen.findByRole('alert')).toHaveTextContent(
/unable to load users/i
);
await user.click(screen.getByRole('button', { name: /retry/i }));
expect(await screen.findByText('Aarav')).toBeInTheDocument();
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
expect(fetchMock).toHaveBeenCalledTimes(2);
});
The mock's mockResolvedValueOnce() method supplies a different response for each request. This lets the test verify that the retry action actually triggers another fetch.
13. Testing That Loading Disappears
When an asynchronous operation finishes, the loading indicator should normally disappear. This prevents users from seeing a permanent loading message after the content has loaded.
it('removes the loading message after success', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: true,
json: async () => [{ id: 1, name: 'Priya' }]
})
);
render(<Users />);
expect(screen.getByRole('status')).toBeInTheDocument();
expect(await screen.findByText('Priya')).toBeInTheDocument();
expect(screen.queryByRole('status')).not.toBeInTheDocument();
});
For more complex cases, waitForElementToBeRemoved() can be used when the test needs to wait specifically for an existing element to disappear.
14. Testing Empty States
An empty state appears when the request succeeds but returns no data. It is different from an error because the server operation completed successfully.
it('shows an empty message when no users are returned', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: true,
json: async () => []
})
);
render(<Users />);
expect(await screen.findByText(/no users found/i))
.toBeInTheDocument();
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});
Testing empty states helps ensure that users receive meaningful feedback even when there is no content to display.
15. Testing Loading and Error States in Forms
Forms often have their own loading and error states while data is being submitted. For example, a login form might disable the submit button during authentication and display an error if the credentials are rejected.
Example Component
import { useState } from 'react';
export default function LoginForm({ login }) {
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [success, setSuccess] = useState('');
async function handleSubmit(event) {
event.preventDefault();
setLoading(true);
setError('');
setSuccess('');
try {
await login();
setSuccess('Login successful');
} catch {
setError('Login failed. Please try again.');
} finally {
setLoading(false);
}
}
return (
<form onSubmit={handleSubmit}>
<button type="submit" disabled={loading}>
{loading ? 'Logging in...' : 'Login'}
</button>
{loading && <p role="status">Please wait...</p>}
{error && <p role="alert">{error}</p>}
{success && <p role="status">{success}</p>}
</form>
);
}
Testing the Loading State During Submission
import userEvent from '@testing-library/user-event';
it('shows a loading state while login is pending', async () => {
const user = userEvent.setup();
let resolveLogin;
const login = vi.fn(() => new Promise((resolve) => {
resolveLogin = resolve;
}));
render(<LoginForm login={login} />);
await user.click(screen.getByRole('button', { name: /^login$/i }));
expect(screen.getByRole('button', { name: /logging in/i }))
.toBeDisabled();
expect(screen.getByRole('status')).toHaveTextContent(/please wait/i);
resolveLogin();
expect(await screen.findByText(/login successful/i))
.toBeInTheDocument();
});
Testing a Failed Form Submission
it('shows an error when login fails', async () => {
const user = userEvent.setup();
const login = vi.fn().mockRejectedValue(new Error('Invalid credentials'));
render(<LoginForm login={login} />);
await user.click(screen.getByRole('button', { name: /^login$/i }));
expect(await screen.findByRole('alert')).toHaveTextContent(
/login failed/i
);
expect(screen.getByRole('button', { name: /^login$/i }))
.toBeEnabled();
});
These tests verify the pending state, button behaviour, successful submission, and error handling. The example focuses on state handling; a real login form should also include accessible username and password fields and appropriate validation.
16. Understanding getBy, queryBy, and findBy
Choosing the correct query is important when testing asynchronous React components.
| Query |
Behaviour |
Typical Use |
getBy... |
Returns an element immediately or throws if it cannot find one. |
Checking a loading message that should already be visible. |
queryBy... |
Returns an element or null. |
Checking that a loading message has disappeared. |
findBy... |
Returns a promise that resolves when the matching element appears. |
Waiting for data or an error message after an API request. |
For example:
// Immediately visible loading state
expect(screen.getByRole('status')).toBeInTheDocument();
// Wait for asynchronous content
expect(await screen.findByText('Aarav')).toBeInTheDocument();
// Verify that the error message is absent
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
Use findBy when an element is expected to appear asynchronously. Use waitFor when you need to retry a more complex assertion that is not conveniently expressed by a single asynchronous query.
17. Testing with waitFor
The waitFor() utility repeatedly runs an assertion until it succeeds or times out. It is useful when several related conditions need to become true after an asynchronous operation.
import { render, screen, waitFor } from '@testing-library/react';
it('updates the interface after loading', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: true,
json: async () => [{ id: 1, name: 'Aarav' }]
})
);
render(<Users />);
await waitFor(() => {
expect(screen.getByText('Aarav')).toBeInTheDocument();
expect(screen.queryByRole('status')).not.toBeInTheDocument();
});
});
Do not put user interactions such as clicks or typing inside a waitFor() callback. Because the callback can run more than once, doing so may cause repeated interactions. Perform the interaction first and then wait for the resulting UI.
18. Testing Error Boundaries
React error boundaries catch certain errors thrown while rendering child components and display fallback UI. They are different from ordinary API error states: an error boundary does not automatically catch every asynchronous error or rejected promise.
A simplified error boundary might display a fallback message when a child throws during rendering. Tests should verify that the fallback appears when a descendant encounters a rendering error.
import { Component } from 'react';
export class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError() {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return <p role="alert">Something went wrong.</p>;
}
return this.props.children;
}
}
When testing error boundaries, remember that React may log errors to the console during the test. Tests can account for expected logging, but should avoid suppressing unrelated errors that could hide genuine failures.
19. Testing Common Failure Scenarios
| Scenario |
Expected Behaviour |
| Request is still pending. |
Loading indicator remains visible. |
| Request succeeds with data. |
Data appears and loading disappears. |
| Request succeeds with an empty array. |
An empty-state message appears. |
| Server returns HTTP 500. |
A user-friendly error appears. |
| Fetch rejects because of a network problem. |
The network failure is handled and an error appears. |
| User clicks Retry. |
A new request is made. |
| Retry succeeds after a failure. |
The error disappears and data is shown. |
| Form submission is pending. |
A loading indicator appears and duplicate submission is prevented where appropriate. |
| Form submission fails. |
An error appears and the user can recover or retry. |
| Component returns no results. |
An empty state appears instead of an error. |
20. Best Practices for Testing Loading and Error States
- Test the initial loading state explicitly.
- Verify that loading indicators disappear after success or failure.
- Test successful API responses and unsuccessful HTTP responses separately.
- Test rejected network requests as a separate failure scenario.
- Use mock functions or a network-mocking tool to control API responses.
- Prefer accessible roles such as
status and alert for status messages.
- Use
findBy for elements that appear asynchronously.
- Use
queryBy to verify that elements are absent.
- Test retry functionality and recovery after a failed request.
- Verify button disabled states during pending operations.
- Ensure error messages are clear and do not expose sensitive technical details.
- Test empty results separately from errors.
- Restore mocked global functions after tests to prevent interference.
- Avoid relying on arbitrary time delays when a promise or asynchronous query can control the test.
- Consider cancellation or stale-response handling for components that can unmount or change requests.
21. Common Mistakes to Avoid
| Mistake |
Correct Approach |
| Assuming fetch rejects for HTTP 500 responses. |
Check response.ok and handle unsuccessful statuses. |
| Using getByText for content that has not appeared yet. |
Use findByText for asynchronous content. |
| Checking only the error message. |
Also verify that loading ends and recovery controls behave correctly. |
| Testing only successful responses. |
Test network failures, server errors, empty results, and retry behaviour. |
| Leaving global fetch mocks in place. |
Restore or reset mocks after each test. |
| Using fixed delays for every asynchronous test. |
Prefer controlled promises and Testing Library async utilities. |
| Showing a technical stack trace to end users. |
Display a clear message and keep technical diagnostics in appropriate logs. |
| Allowing repeated submissions unintentionally. |
Test pending-state behaviour and prevent duplicate requests where needed. |
22. Practical Project: User Dashboard
Create a simple user dashboard that fetches user data and displays appropriate feedback for each request state.
Project Requirements
- Show "Loading users..." while the request is pending.
- Display a list of users after a successful response.
- Display "No users found" when the API returns an empty array.
- Show an error message when the request fails.
- Provide a Retry button when an error occurs.
- Remove the error message when a retry succeeds.
- Test each state using React Testing Library and Vitest.
Suggested Test Cases
- Verify that the initial loading message is displayed.
- Verify that returned user names are visible.
- Verify that loading disappears after success.
- Verify that a server error displays an alert.
- Verify that a network rejection displays an alert.
- Verify that an empty response displays the empty-state message.
- Verify that clicking Retry makes another request.
- Verify that successful retry removes the error and displays data.
Running the Tests
npm test
To run the Vitest suite once without watch mode, use:
npm run test:run
Review failed assertions, component warnings, and unhandled promise rejections. Update the component or test based on the actual problem rather than hiding the failure.
23. Interview Questions and Answers
Q1. What is a loading state in React?
A loading state is UI feedback displayed while an asynchronous task, such as an API request, is in progress.
Q2. What is an error state?
An error state informs users that an operation could not be completed and may provide a retry or recovery option.
Q3. Why should loading states be tested?
Testing ensures that users receive feedback during pending operations and that loading indicators disappear when the operation completes.
Q4. How do you test an error message?
Mock the failed operation, render the component, and use an assertion such as await screen.findByRole('alert') to verify the displayed error.
Q5. What is the difference between an HTTP error and a network error?
An HTTP error is an unsuccessful server response, such as status 500. A network error occurs when the request itself fails and may reject its promise.
Q6. Why check response.ok when using fetch?
The fetch promise normally resolves for HTTP error statuses. Checking response.ok helps the application handle unsuccessful HTTP responses explicitly.
Q7. What is the purpose of findBy queries?
They wait for an element to appear and return a promise that resolves when the matching element is found.
Q8. When should queryBy be used?
It is useful for checking that an element is absent because it returns null when no matching element exists.
Q9. How do you test a retry button?
Simulate an initial failed request, click Retry, return a successful response, and verify that the content appears and the error disappears.
Q10. What is an empty state?
An empty state is displayed when an operation succeeds but returns no items or content.
Q11. What is the difference between an API error state and an error boundary?
An API error state is usually managed by application logic for failed requests. An error boundary catches certain rendering and lifecycle errors in descendant components.
Q12. What should be tested during form submission?
Test the pending indicator, disabled button behaviour, success message, failure message, and whether the user can retry when appropriate.
24. Revision Checklist
- Understand loading, success, error, and empty states.
- Know how to configure React Testing Library and Vitest.
- Test the initial loading message.
- Test successful data loading.
- Test HTTP error responses.
- Test rejected network requests.
- Verify that loading indicators disappear.
- Test retry behaviour and recovery.
- Test form submission loading and error feedback.
- Understand the difference between
getBy, queryBy, and findBy.
- Use
waitFor when a complex asynchronous assertion requires retrying.
- Test empty states separately from error states.
- Clean up mocks between tests.
- Run the full test suite before releasing changes.
25. Official Learning Resources
26. Conclusion
Testing loading and error states helps React applications handle asynchronous operations reliably. A complete test suite should verify pending requests, successful responses, HTTP errors, network failures, empty results, and retry behaviour. Using React Testing Library, user-event, Vitest, and accessible status messages helps developers write tests that reflect real user experiences and make applications easier to maintain.
To continue learning React development, visit the JustAcademy React JS Training Course or Register for React JS Course Demo.