Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsYou can test a React component’s API error UI without a live backend by using Mock Service Worker (MSW) to intercept its request and return a controlled failure. Keep the component’s real request code in place, then test an HTTP error such as a 500 separately from a network failure: the first is an HTTP response, while the second rejects the fetch.
What to test: HTTP errors versus network failures
A 500 response is still a successful network exchange: the client receives an HTTP response whose status indicates failure. With native fetch, a non-2xx response does not automatically reject the promise. Your request code must check response.ok or the status and route the result into the application’s error handling.
As an Amazon Associate I earn from qualifying purchases.
A network failure is different. No usable HTTP response arrives, and the fetch promise rejects. MSW’s network-error documentation says Fetch provides no way to customize the network error message; clients receive a generic TypeError: Failed to fetch, which belongs in the request’s catch path.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minute| Scenario | What the request does | What the test should exercise |
|---|---|---|
| HTTP error, such as 500 | Receives a response; application code handles its status. | The status-handling path and the resulting user-visible error. |
| Network failure | Rejects without a usable HTTP response. | The rejection or catch path and the resulting user-visible error. |
Test both when they lead to different product behavior. MSW also documents network-error simulation for situations such as DNS errors, connection timeouts, and offline clients.
Set up MSW for component tests
For Node-based component tests, define handlers with http and HttpResponse, and initialize an MSW server for the test suite. The normal handler can return a successful response; an individual test can override it with a failure. React Testing Library’s official example recommends MSW for declarative API mocking rather than stubbing window.fetch or relying on third-party adapters.
import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'
import { render, screen, fireEvent } from '@testing-library/react'
import '@testing-library/jest-dom'
import Fetch from './Fetch'
const server = setupServer(
http.get('/api/greeting', () => HttpResponse.json({ greeting: 'hello' })),
)
beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())
Use the method and URL the component actually requests. Keeping its production request code intact lets the test exercise the normal client and state logic. The setup and endpoint above are illustrative: adapt the component, request semantics, and accessible names to your application. MSW describes reusing request handlers in tests, local development, and other contexts in its project documentation.
Test an HTTP 500 response
Override the matching handler for the test and return an HTTP response with status 500. Then render the component, trigger the action as a user would, and wait for the error UI.
Rank #2
test('shows a recoverable error when the API returns 500', async () => {
server.use(
http.get('/api/greeting', () => new HttpResponse(null, { status: 500 })),
)
render(<Fetch />)
fireEvent.click(screen.getByRole('button', { name: /load/i }))
const alert = await screen.findByRole('alert')
expect(alert).toHaveTextContent(/failed/i)
expect(screen.getByRole('button', { name: /load/i })).toBeEnabled()
})
The component must turn the response status into the error state; MSW supplies the response but does not decide how your application interprets it. If your request layer reads an error body or distinguishes status codes, return the relevant body or use the status that matches that behavior. Test 4xx and 5xx cases separately when the UI responds differently.
Test a rejected fetch
To simulate a network-level failure, use HttpResponse.error() rather than returning a 500. This makes the request reject, so the component’s rejection or catch handling must produce the accessible error state.
test('shows an error when the network request fails', async () => {
server.use(
http.get('/api/greeting', () => HttpResponse.error()),
)
render(<Fetch />)
fireEvent.click(screen.getByRole('button', { name: /load/i }))
expect(await screen.findByRole('alert')).toBeVisible()
})
MSW’s response-mocking guide recommends HttpResponse for mocked responses and documents how it differs from the standard Fetch Response. Use the API supported by the MSW version in your project.
Rank #3
Assert the experience, including recovery
Prefer assertions about what a user can perceive over checks of internal state fields or only whether a request function was called. Testing Library’s example waits for an alert, checks its text, and verifies the button is enabled after failure. Choose the assertions that match the component’s intended behavior:
- Wait for an accessible error message, such as an element with
role="alert", and verify its useful text. - If the request displays a loading indicator, verify that it ends when the error appears.
- If the product offers retry, test that action and its resulting state; otherwise, check whether the submit or load control becomes available again.
- When error categories have different messaging or recovery, verify each category independently.
Reset test-specific handler overrides after each test so one failure scenario cannot leak into another. Close the MSW server after the suite, as in the setup above.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Check loading-to-error behavior when it matters
If the UI has a meaningful loading state, test the transition as well as the final error. A delayed MSW response lets the test observe the pending presentation before the controlled failure arrives. React Navigation’s testing guide demonstrates using MSW delay for deterministic mocked requests. Keep the delay limited to a test that needs to inspect the loading state; a test concerned only with the final error can wait directly for the alert.
Check the test runner’s fetch support
A missing fetch implementation can look like an application or MSW problem. React Testing Library notes that JSDOM does not include fetch by default; its current example says Vitest includes fetch, while Jest may require a polyfill or an environment such as jest-fixed-jsdom. Check the runner and versions actually used by your project before changing the mock or component code.
Know what a mocked test proves
An MSW-backed component test shows how the frontend behaves for the controlled responses and failures you configured. It does not establish that a deployed backend is healthy, that production connectivity works, or that full-stack side effects succeed. React’s testing environments guide notes that critical end-to-end workflows may also be checked in a real browser against real API endpoints.
Recommended Free Tools
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




