Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk4 min

Test React API Errors Without a Backend: MSW Patterns That Work

Intercept React API requests with MSW to test accessible error messages, HTTP failures, network rejections, loading states, and recovery without a live backend.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

You 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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

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:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • 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.Support on Ko-Fi

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.