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 errorsiTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
You can test React API error states without a live backend by using Mock Service Worker (MSW) to intercept the component’s request and return a controlled failure. Render the real component, trigger its normal request, and assert the accessible error message and recovery behavior. Test an HTTP error such as 500 separately from a network failure: the first is a response, while the second rejects the request.
Why intercept the request instead of mocking a function?
MSW lets the component use its ordinary request code while the test controls what comes back at the network boundary. That exercises the path from user action through the request and into React’s rendered state, without requiring a running API. React Testing Library recommends MSW for mocking API communication rather than stubbing window.fetch or relying on third-party adapters: React Testing Library’s example. MSW says its request handlers can be reused across testing, local development, and other contexts: MSW project documentation.
The examples below use MSW’s current http and HttpResponse APIs. Adapt the method, URL, button name, and expected message to the application; the snippet is a pattern, not a verified drop-in test.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Set up a Node MSW server for component tests
For Node-based component tests, create a server with setupServer, provide a default handler for the endpoint, and manage the server and overrides for the suite:
#1 Best Overall
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 exact method and URL the component requests. The default successful handler gives the server a defined response outside tests that override it. Resetting handlers after each test prevents a failure scenario from leaking into another test; closing the server after the suite completes its lifecycle.
How do you test an HTTP 500 response?
A 500 is an HTTP response, not a network failure. Return a response with that status and let the component’s normal request layer process it. With native fetch, a non-2xx response does not automatically reject the promise: application code must check the status and enter its error path, unless a request wrapper already does that.
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()
})
findByRole waits asynchronously for the alert to appear. The test checks user-visible output and that the control is available again, rather than inspecting internal component state. If the application distinguishes status classes or uses an error response body, add handlers and assertions for those behaviors.
How do you test a network failure?
For a network-level failure, no usable HTTP response reaches the client. MSW’s HttpResponse.error() simulates that case, which follows a rejected-fetch path rather than the status-check path used for a 500:
Rank #3
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()
})
The MSW documentation explains that the Fetch API does not let callers customize the network-error message; clients receive a generic TypeError: Failed to fetch, which should be handled in the request’s catch path: MSW network errors. Assert the application’s useful error UI, not that exact runtime message, unless exposing it is an intentional product behavior.
What should an API error test assert?
Choose assertions based on what a person using the interface should experience. A useful failure test can verify:
Rank #4
- An accessible alert or other appropriate error role appears with meaningful text.
- A loading indicator stops or the loading presentation changes to the error presentation.
- The submit or retry control returns to the correct enabled state.
- A retry action, if present, can be used and produces the expected next state.
Use distinct tests for HTTP statuses or network failures when they lead to different product behavior. Avoid checking private state fields or merely asserting that a request function was called: neither establishes that the error is communicated accessibly or that the interface recovers.
Test loading transitions when timing matters
If the loading state itself matters, use an MSW delay so the test can observe the pending UI before the controlled failure arrives. React Navigation’s testing guide demonstrates delayed MSW responses for deterministic mocked requests: React Navigation testing. Keep the delay focused on the behavior under test rather than relying on real network timing.
Best Value
What can these tests prove?
MSW-based component tests establish how the frontend behaves for the scenarios configured in the test: the error path, rendered message, loading transition, and recovery controls. They do not establish that a deployed API is healthy, that production connectivity works, or that full-stack side effects succeed. React’s testing-environments guidance notes that critical end-to-end workflows may also use a real browser and API endpoints: React Testing Environments.
What to check if the test fails before the error appears
- Confirm the handler matches the request. Check that its HTTP method and URL match what the component actually sends.
- Check the request’s error handling. A 500 response must be converted into an application error state; with fetch, status failures do not reject automatically.
- Check the test runtime’s fetch support. Testing Library notes that JSDOM does not include
fetchby default. Its example says Vitest includes fetch, while Jest may need a polyfill or an environment such asjest-fixed-jsdom. Verify the project’s runner and versions before changing setup: Testing Library setup notes. - Confirm cleanup and isolation. Ensure
server.resetHandlers()runs after each test so an override does not affect later scenarios.
MSW supports common request clients such as native fetch, Axios, React Query, and Apollo. Its browser implementation uses service-worker interception; Node tests use a different interception implementation. See the MSW project documentation for the project’s current details.
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.
Recommended Free Tools

