Test fetch HTTP errors with Node.js
Your API sometimes returns an HTML maintenance page. The UI reports a JSON syntax error, so the agent offers to rewrite your JSON parser. Reproduce what arrived over HTTP before authorizing a redesign of punctuation.
- Before you start
- Node.js 22 or later and two .mjs files in an empty directory. No npm install or internet access is needed to run the tests.
- What to verify
- Distinguish HTTP failure from network failure, and keep a successful JSON response intact.
Start with the plausible bug
Save this function in seat.mjs. Its optional argument accepts a function with the same calling convention as fetch. Production callers can omit that argument. Tests will pass a small replacement that returns a real Response object. The reserved example domain is just a string in these tests.
export async function loadSeat(fetcher = fetch) {
const response = await fetcher('https://example.test/seat');
return response.json();
}Do not call the function without the stub in this lab. The comparison we care about happens entirely in memory.
Separate three different contracts
Write one test per outcome. The success case fixes the expected data shape. The HTTP failure deliberately contains HTML, just like a maintenance page. The last case rejects before a response exists. Comparing the error by identity verifies that the wrapper preserves the rejection it received.
import test from 'node:test';
import assert from 'node:assert/strict';
import { loadSeat } from './seat.mjs';
test('200 returns the seat', async () => {
const reply = async () => Response.json({ id: 'V2' });
assert.deepEqual(await loadSeat(reply), { id: 'V2' });
});
test('503 reports the status before parsing an HTML body', async () => {
const reply = async () => new Response('<h1>Busy</h1>', { status: 503 });
await assert.rejects(loadSeat(reply), /HTTP 503/);
});
test('network failure reaches the caller', async () => {
const offline = new TypeError('offline');
const reply = async () => { throw offline; };
await assert.rejects(loadSeat(reply), error => error === offline);
});Using an HTML body makes the order of operations observable. If parsing happens too early, the second test receives a syntax error.
Read the failure once
Run the command below. Expect two passes and one failure. Read the failure for 503 first. Fetch can successfully deliver an HTTP response with a failing status code. A transport failure rejects the promise instead. If your assistant treats both as a successful empty array, users will see a reassuringly empty warehouse during every outage.
node --test seat.test.mjsKeep this red output. It gives the agent a precise error contract to implement and gives you a comparison after the change.
Check the status before reading the body
Replace seat.mjs with this version and run the same command. All three tests should pass. The failure branch reads the numeric status while the response is still available. The success branch retains the original JSON parsing, so an invalid success body still fails instead of being silently swallowed.
export async function loadSeat(fetcher = fetch) {
const response = await fetcher('https://example.test/seat');
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
}For another round, construct a Response with status 429 and add a test for HTTP 429. It should pass without changing the wrapper. A retry policy is a separate product decision.
Try this prompt with your agent
Here is my fetch wrapper and its three tests. Explain the failing 503 case before editing. Keep success JSON unchanged and propagate transport errors. Propose the smallest patch, then show what happens with a 429 response.A trap worth catching
An async stub that throws for HTTP 503 models a network failure. Return a Response with status 503 to exercise the HTTP branch.