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

For tests that should exercise your application’s normal request code, use Mock Service Worker (MSW) to intercept requests where your test runtime supports it. For a small unit test that only needs to check how a function calls or responds to fetch, a direct mock is also a reasonable choice. The key is to test the failure you mean: an HTTP 404 response is not the same as a rejected network request.

Choose between MSW and a direct fetch mock

Approach What it replaces Best fit Trade-off
MSW request interception Intercepts the outgoing request while leaving the application’s ordinary request path in place. Tests that should model realistic request and response behavior, including headers, status codes, and network failures. Requires reusable request handlers and test-runner lifecycle setup.
Direct function mock Replaces the fetch function with a mock that resolves or rejects as specified. A narrowly isolated unit test checking a function’s fetch-call contract or its handling of a returned value. You must supply the response methods your code calls; the test models the function boundary rather than intercepting a request.

Vitest’s request-mocking guide recommends MSW for network request mocking and describes Node interception through @mswjs/interceptors. MSW’s Node.js integration guide names both Jest and Vitest. Choose based on what the test needs to preserve, not on a universal rule.

Set up MSW for Vitest

Keep handlers reusable and separate from runner setup. The following TypeScript adaptation uses the documented MSW Node setup pattern and Vitest lifecycle hooks. Add its setup file to Vitest’s setupFiles configuration; check the imports and APIs against the versions installed in your project.

// test/server.ts
import { afterAll, afterEach, beforeAll } from 'vitest'
import { setupServer } from 'msw/node'
import { http, HttpResponse } from 'msw'

export const server = setupServer(
  http.get('https://api.example.test/items', () =>
    HttpResponse.json([{ id: 'item-1' }]),
  ),
)

beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))
afterEach(() => server.resetHandlers())
afterAll(() => server.close())

Starting the server before tests, resetting per-test overrides afterward, and closing the server when the suite finishes keeps one test’s handler from leaking into another. With onUnhandledRequest: 'error', an unhandled request fails rather than silently escaping as an accidental real network call; see the Vitest lifecycle guidance. MSW’s quick start shows handlers built with http.get and HttpResponse.json, then passed to setupServer for Node.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Test a successful response

Call the production function and assert its observable result. For example, suppose getItems fetches the endpoint and returns the parsed JSON:

export async function getItems(): Promise<{ id: string }[]> {
  const response = await fetch('https://api.example.test/items')
  if (!response.ok) {
    throw new Error(`Request failed: ${response.status}`)
  }
  return response.json()
}

A test can exercise that ordinary function without replacing fetch:

import { expect, it } from 'vitest'
import { getItems } from '../src/items'

it('returns items from the API', async () => {
  await expect(getItems()).resolves.toEqual([{ id: 'item-1' }])
})

The registered handler supplies the JSON response. This follows the MSW quick-start pattern, which demonstrates fetching a registered endpoint and asserting on the parsed response.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Test an HTTP error status such as 404

A 404 or 500 is still an HTTP response. Fetch does not turn a non-OK status into a rejected promise by itself, so a function that should reject on such a status needs an explicit response.ok or status check. The example above throws its own error for that reason.

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

Override the handler with a response carrying the status you want to exercise:

import { expect, it } from 'vitest'
import { http, HttpResponse } from 'msw'
import { server } from '../test/server'
import { getItems } from '../src/items'

it('throws when the API returns 404', async () => {
  server.use(
    http.get('https://api.example.test/items', () =>
      new HttpResponse(null, { status: 404 }),
    ),
  )

  await expect(getItems()).rejects.toThrow('Request failed: 404')
})

Because the setup calls server.resetHandlers() after each test, this override is temporary.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Test a rejected request or network failure

A network failure is a different input: the request itself rejects instead of resolving to an HTTP response. MSW documents HttpResponse.error() for simulating this case. The client receives the generic TypeError: Failed to fetch; the API does not let you customize that message, so avoid asserting DNS- or timeout-specific wording. See MSW’s network errors guide.

import { expect, it } from 'vitest'
import { http, HttpResponse } from 'msw'
import { server } from '../test/server'
import { getItems } from '../src/items'

it('rejects when the request fails at the network level', async () => {
  server.use(
    http.get('https://api.example.test/items', () => HttpResponse.error()),
  )

  await expect(getItems()).rejects.toThrow()
})

If you are testing an error state rather than a rejected promise directly, assert the state your application exposes—for example, that a caller receives an error result or that a UI renders its failure state. Keep that assertion about your function’s behavior, not a particular network stack’s wording.

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

Handle caught values safely in TypeScript

TypeScript code should not assume that every caught value is an Error. JavaScript permits throwing values of other types, so narrow an unknown value before reading .message:

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
try {
  await getItems()
} catch (error: unknown) {
  const message = error instanceof Error ? error.message : 'Unexpected failure'
  // Report or return message
}

This is a TypeScript safety practice; it does not change whether the underlying failure was an HTTP response or a rejected request.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use a direct Jest mock when the function boundary is the point

For a focused unit test, mock the fetch dependency with a promise that resolves to the response shape the production code actually uses. If that code calls response.json(), the mock needs a json method; if it calls response.text(), it needs text. A simple mocked response might look like this:

const fetchMock = jest.fn().mockResolvedValue({
  ok: true,
  json: async () => [{ id: 'item-1' }],
})

Wire the mock through the module or dependency boundary used by your function, then assert the result and, if relevant, the request arguments. A mock of fetch is not automatically a complete Fetch Response.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Jest’s “Bypassing module mocks” guide documents a specific node-fetch pitfall: mocking node-fetch can also mock its Response, leaving methods such as response.text() unavailable. Its example retrieves the real response with jest.requireActual. That concern is specific to the module-mocking setup described there; do not assume a node-fetch response and a runtime’s global Fetch API are interchangeable.

Keep aborts distinct from network errors

Cancellation is another case, separate from both an HTTP error status and a generic network rejection. The node-fetch documentation describes abort rejections as AbortError and other operational errors as FetchError (node-fetch error handling). That taxonomy applies to node-fetch; it should not be generalized to browser Fetch or every runtime. If your function supports cancellation, give it a separate test using the cancellation mechanism and runtime your application actually uses.

Check the test runtime before choosing globals

Available web APIs depend on the test environment. Vitest’s request-mocking guide notes the effect of its Node environment and presents MSW as a way to mimic network behavior. Confirm which fetch and response implementation the project uses before writing direct mocks—especially when a project imports node-fetch instead of relying on a global. The examples here illustrate patterns; they are not a claim that a specific package-version combination was executed.

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.

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