Write two tests if your code handles both HTTP errors and a failed connection. For an HTTP 503, await fetch() and assert that the response has ok === false and status === 503. For a connection that closes before response headers arrive, assert that the fetch promise rejects. A local HTTP server lets you produce both situations without relying on an external service or waiting for a real outage.
Decide what each test should prove
A server can successfully send an HTTP response that describes a failure. The promise returned by fetch() still resolves with a Response, and the application can inspect its status or body.
The lack of an HTTP response is a different situation. When the connection closes before getting headers, the fetch promise can reject, and there is no status to read from it.
Keeping the cases separate makes the assertion tell you what broke. If you use assert.rejects() in both tests, you may end up asserting that the fixture accidentally failed to start. If you look only at response.ok in both tests, the test has no response to inspect in the connection-failure case.
Run this file with the built-in test runner
Save the example as fetch-errors.test.mjs. It uses Node’s HTTP server, built-in test runner, and global fetch. The server listens on the loopback address and asks the operating system for a temporary port. Each test closes its server through a teardown callback.

import assert from 'node:assert/strict';
import { once } from 'node:events';
import { createServer } from 'node:http';
import { test } from 'node:test';
test('a 503 resolves with an HTTP error response', async (t) => {
const server = createServer((_request, response) => {
response.writeHead(503, { 'content-type': 'text/plain' });
response.end('Try later');
});
t.after(() => new Promise((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve());
}));
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const { port } = server.address();
const response = await fetch('http://127.0.0.1:' + port + '/status');
assert.equal(response.ok, false);
assert.equal(response.status, 503);
assert.equal(await response.text(), 'Try later');
});
test('a dropped connection rejects fetch before headers arrive', async (t) => {
let handled = false;
const server = createServer((request) => {
handled = true;
request.socket.destroy();
});
t.after(() => new Promise((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve());
}));
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const { port } = server.address();
await assert.rejects(
() => fetch('http://127.0.0.1:' + port + '/disconnect'),
TypeError,
);
assert.equal(handled, true);
});
Run it in a terminal from the folder containing the file. Node should report two passing tests.
node --test fetch-errors.test.mjs
If the runner reports spawn EPERM on Node.js 22, try the in-process command below. It runs the same assertions without launching an isolated test process.
node --test --experimental-test-isolation=none fetch-errors.test.mjs
If you see an error about binding a socket, check whether your execution environment permits localhost listeners. Running the same file in a local terminal that permits loopback is a straightforward check.

This fixture needs a modern Node release that supports both global fetch and the test runner. Node.js test runner · Node.js global fetch
Follow the HTTP response through the first test
The server writes a 503 status and sends the text Try later. The test awaits fetch(), which should return a response. The next assertions check both the broad result and the exact situation: ok is false and the status is 503. Reading the body checks what the server actually returned and consumes the response.
A 404 and a 503 are both outside the success range, but they can mean different things to the application. If a branch handles 503 specifically, make the fixture send exactly that status.
A separate test can cover 404 if the application treats it differently. This keeps the test focused on an observable decision rather than any random non-success response.
Follow the rejected promise through the second test
The second server accepts an HTTP request and destroys the socket without writing headers. The request is made after the listening event, so the test is intentionally breaking the connection during the request.
Passing a function to assert.rejects() makes the promise being tested explicit. The check uses TypeError in the tested Node implementation and avoids pinning a dependency’s full error message.
This test covers the failure before headers. There are also cases where fetch resolves with headers and reading the body rejects later. If your app needs to handle a dropped download, design a separate case that sends headers and only part of the body. Assert the promise your production code actually awaits.
Adapt the assertions to your application
The current file demonstrates the boundary directly. In an application test, you can call your own request helper with the same local URL and assert what the helper exposes.
For a 503, perhaps it returns a service-unavailable outcome or throws a custom error carrying the status. For the connection drop, perhaps it raises a separate error with no status. The fixture stays useful even when your production API has a different shape.
If your helper retries, keep those tests bounded. Set the retry count explicitly and define whether you intend to verify one response, eventual recovery, or exhausted attempts.
You can have a local server return 503 once and a success on the next request if the behaviour under test is recovery. Track the request count in the fixture for that test so it has evidence of the retry.
Diagnose a failing fixture
Start by checking the order. Wait for the server to listen before reading its address. Build the URL from the address that was assigned, rather than assuming a fixed port. Bind and fetch the same address.
A spelling mistake in the host or port can turn an HTTP-status test into a rejected promise for an unrelated reason.
If the tests appear to pass but the process hangs, check teardown and pending response bodies. The examples register cleanup before awaiting fetch and consume the body in the HTTP case.
Keep each fixture inside its own test so its state is easy to inspect. For request timing and connection diagnosis, see the Chrome DevTools Network waterfall walkthrough.
Confirm that the fixture took the path you intended
A rejected promise tells you an operation failed. Make sure the failure came from your test server. The second test tracks whether the request handler ran before it closed the socket.
If fetch rejects because the URL is wrong, the handler flag never changes, and the test fails at the flag assertion. This gives you evidence that the request reached the fixture and the connection was closed at the planned point.
Keep the fixture small enough that you can see what it sends by looking at it. The first handler writes one status, one header, and one short body. The second handler writes no response and destroys the connection.
If you add more routes later, give your test a known endpoint and make unexpected requests visible. This is especially helpful if you collect request counts or check the method and path that a request helper sends.
Decide how much to assert for each layer
If you are testing a helper that returns a raw response, assert the status and check the body if that content drives a caller decision. If the helper returns an object with a state or throws a custom error, test that contract instead.
For instance, a service helper could convert a 503 into a temporary-failure outcome and preserve its numeric status. A different call could translate a rejected fetch into an offline outcome. Keep the test names aligned with what the caller sees so a failure is easy to interpret.
An application that renders loading, empty, and error states has another layer to test. The server test can prove what your request helper does, then a UI test can supply that result and check what a user sees.
The CyboGeek walkthrough of Fetch loading, empty, and error states covers that view layer. Keeping the data boundary and feedback checks separate means a failure comes with a smaller set of things to inspect.
Know which await belongs to a new test
The server sends headers, then stops mid-body
The initial fetch can resolve with a response once headers arrive. The time to catch a later read failure is when your code awaits body consumption. If your actual code uses response.json or response.text, design the test around that promise.
You can write a specific local fixture to send a body prefix, then close the connection deliberately. Keep this as its own case so a failure tells you whether headers or body consumption was involved.
The user cancels a request
Treat a cancellation as a separate input if your application supports it. Trigger it through the same cancellation path your code actually uses and assert the observable result after that event.
For example, a UI might dismiss a pending indicator without showing an error. Throwing a socket error in a separate test will still exercise another case. Make sure the test uses a bounded wait and stops any work it started.
A non-success response carries useful details
If your service sends JSON along with its 503, give the HTTP fixture a body that represents the fields your application reads. Check the status and the relevant fields rather than copying all the details of a real incident into your fixture.
To check malformed JSON, use a separate case that deliberately sends badly formed contents. That lets you tell an HTTP-status branch from a parse branch when reading the test report.
Rerun the tests and read them as evidence
Run the file twice after you add your own app helper. Both passes should tell the same story even if the assigned port changes. Look at the failure output while you temporarily change the expected status in the first test to 500. It should identify the status assertion.
Restore 503, then try commenting out the socket closure only if you give the trial a bounded timeout and keep the change local. For an easier check, change the expected handler flag and confirm that the exact assertion points to the route check.
Each temporary edit should be restored before you keep the fixture or share it with a colleague. Save the final output from the passing code as the test record. That way, the command shown in the article, the source file, and the reported result all refer to the same two cases.
If you keep the fixture with the repository, put the run command next to the test file so the next reader can repeat it after a Node upgrade.
Rerun the two tests after changing the request code. The first should still tell you what happens when a server answers with a 503. The second should still tell you what happens when there is no response to inspect.
