Sub topic 16
Testing That Your Functions Really Cancel
A cancellable function can look right and still be broken. It might reject on abort but leave its timer running. It might work for a mid-flight abort but ignore an already-aborted signal. It might drop the abort reason and throw a generic error instead. Tests catch these problems before your callers do.
This chapter assumes you are comfortable with promises, async/await, and the delay(), fetchAll(), and fetchJson() functions from earlier chapters. The examples use Node.js 22 or later and its built-in test runner (node:test), so you need no extra packages. The same ideas carry over to Jest or Vitest.
What a Cancellation Test Must Prove
A function that accepts a signal makes a contract with its caller. Each part of that contract needs its own test:
| Situation | Expected behavior | What to assert |
|---|---|---|
| Signal already aborted | Reject at once, start no work | Rejects with `signal.reason`; no timer or request started |
| Abort while work is running | Stop work, reject with the reason | Rejects with the same reason object; timer cleared |
| Work finishes normally | Resolve, then detach from the signal | Abort listener removed |
| Custom reason passed to `abort()` | Surface that exact value | Rejection `===` the custom reason |
| Signal forwarded to nested calls | Inner work sees the same signal | Inner call received the signal; later steps skipped |
| Timeout versus user abort | Different errors for the caller | `TimeoutError` wrapped, `AbortError` passed through |
| No signal at all | Works normally | Resolves |
The Code Under Test
Put the functions from earlier chapters in one module so the tests can import them.
// cancellable.js
export function delay(ms, { signal } = {}) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason);
return;
}
const onAbort = () => {
clearTimeout(timerId);
reject(signal.reason);
};
const timerId = setTimeout(() => {
signal?.removeEventListener('abort', onAbort);
resolve();
}, ms);
signal?.addEventListener('abort', onAbort, { once: true });
});
}
export async function fetchAll(urls, { signal } = {}) {
const results = [];
for (const url of urls) {
signal?.throwIfAborted();
const response = await fetch(url, { signal });
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
results.push(await response.json());
}
return results;
}
export async function fetchJson(url, { signal, timeoutMs = 5000 } = {}) {
const timeoutSignal = AbortSignal.timeout(timeoutMs);
const combined = signal
? AbortSignal.any([signal, timeoutSignal])
: timeoutSignal;
try {
const response = await fetch(url, { signal: combined });
return await response.json();
} catch (err) {
if (err.name === 'TimeoutError') {
throw new Error(`Timed out after ${timeoutMs} ms`, { cause: err });
}
throw err;
}
}Testing the Three Moments of delay()
The key tool is a spy, which is a wrapper that records each call to a function and still runs the original. In node:test, t.mock.method(object, name) installs a spy and removes it automatically when the test ends.
// cancellable.test.js
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { delay, fetchAll, fetchJson } from './cancellable.js';
test('delay rejects at once when the signal is already aborted', async (t) => {
const setTimeoutSpy = t.mock.method(globalThis, 'setTimeout');
const controller = new AbortController();
controller.abort();
const promise = delay(1000, { signal: controller.signal });
// Checked synchronously, before anything else can call setTimeout.
assert.equal(setTimeoutSpy.mock.callCount(), 0);
await assert.rejects(promise, (err) => {
assert.equal(err, controller.signal.reason);
assert.equal(err.name, 'AbortError');
return true;
});
});
test('delay clears its timer and rejects with the reason on abort', async (t) => {
const clearTimeoutSpy = t.mock.method(globalThis, 'clearTimeout');
const controller = new AbortController();
const promise = delay(60_000, { signal: controller.signal });
controller.abort();
await assert.rejects(promise, (err) => err === controller.signal.reason);
assert.equal(clearTimeoutSpy.mock.callCount(), 1);
});
test('delay removes its abort listener when it resolves', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
const { signal } = new AbortController();
const addSpy = t.mock.method(signal, 'addEventListener');
const removeSpy = t.mock.method(signal, 'removeEventListener');
const promise = delay(1000, { signal });
t.mock.timers.tick(1000);
await promise;
assert.equal(removeSpy.mock.callCount(), 1);
const [type, listener] = removeSpy.mock.calls[0].arguments;
assert.equal(type, 'abort');
// The removed listener must be the exact function that was added.
assert.equal(listener, addSpy.mock.calls[0].arguments[1]);
});
test('delay surfaces a custom abort reason unchanged', async () => {
const controller = new AbortController();
const reason = new Error('User navigated away');
const promise = delay(60_000, { signal: controller.signal });
controller.abort(reason);
await assert.rejects(promise, (err) => err === reason);
});
test('delay works without a signal', async () => {
await delay(5);
});Some details here matter:
- Assert identity, not just type.
err === controller.signal.reasonproves the function passed the reason through. A check likeerr instanceof Errorwould also pass for a function that throwsnew Error('aborted'), and that function breaks callers who checkerr.name. - Compare listener references. The success-path test checks that the removed listener is the same function that was added. If the code removed a fresh arrow function by mistake,
removeEventListenerwould silently do nothing, and a call-count check alone would miss it. - Mock timers make waiting instant.
t.mock.timers.enable()replacessetTimeoutwith a fake clock, andtick(1000)fires the timer immediately, so the 1000 ms test runs in microseconds.
Testing Signal Forwarding With a Fake fetch
You should not hit the network in unit tests. Replace fetch with a fake that behaves like the real one around cancellation: it rejects with signal.reason when the signal aborts and never resolves on its own. A fake like that lets you control exactly when the "request" ends.
// Append to cancellable.test.js
function hangingFetch(calls) {
return (url, { signal } = {}) => {
calls.push({ url, signal });
return new Promise((_, reject) => {
if (signal?.aborted) {
reject(signal.reason);
return;
}
signal?.addEventListener('abort', () => reject(signal.reason), { once: true });
});
};
}
test('fetchAll forwards the signal and stops the loop on abort', async (t) => {
const calls = [];
t.mock.method(globalThis, 'fetch', hangingFetch(calls));
const controller = new AbortController();
const promise = fetchAll(['/a', '/b', '/c'], { signal: controller.signal });
controller.abort();
await assert.rejects(promise, { name: 'AbortError' });
assert.equal(calls.length, 1);
assert.equal(calls[0].signal, controller.signal);
});
test('fetchJson turns a timeout into a descriptive error', async (t) => {
t.mock.method(globalThis, 'fetch', hangingFetch([]));
await assert.rejects(fetchJson('/slow', { timeoutMs: 20 }), (err) => {
assert.equal(err.message, 'Timed out after 20 ms');
assert.equal(err.cause.name, 'TimeoutError');
return true;
});
});
test('fetchJson passes caller cancellation through unchanged', async (t) => {
t.mock.method(globalThis, 'fetch', hangingFetch([]));
const controller = new AbortController();
const promise = fetchJson('/slow', { signal: controller.signal });
controller.abort();
await assert.rejects(promise, { name: 'AbortError' });
});Run everything with:
node --testThe forwarding test makes two separate claims. calls[0].signal === controller.signal proves the signal reached fetch. calls.length === 1 proves the loop stopped and never requested /b or /c. Without the throwIfAborted() checkpoint, the loop would still stop here, because the rejected fetch throws out of it. Write a separate test that aborts between iterations if you want to pin down the checkpoint itself.
Common Mistakes in Cancellation Tests
- Aborting before attaching a handler, then awaiting later. Code like
const p = delay(...); controller.abort(); await somethingElse(); await assert.rejects(p)can trigger an unhandled-rejection warning. Pass the promise toassert.rejectsbefore any otherawait. - Testing only the happy path. A function with no abort handling at all passes every test that never calls
abort(). - Forgetting the already-aborted case.
addEventListener('abort', ...)on an aborted signal never fires, so a function that skips the early check hangs forever. Without a test timeout, the test hangs too. Set{ timeout: 1000 }on cancellation tests so a hang fails the test quickly. - Matching on error messages. Messages from
DOMExceptioncan differ between runtimes. Checkerr.nameor object identity instead.
Exercise
A teammate's delay() passes the mid-flight abort test but hangs when called with an already-aborted signal. What is missing from their code, and which test catches it?
Show answer
They skipped the early if (signal?.aborted) check. An abort event never fires on a signal that is already aborted, so the listener never runs and the promise never settles. The "rejects at once when the signal is already aborted" test catches it, ideally with a test timeout such as { timeout: 1000 } so the hang fails fast.
Exercise
Write a test proving that fetchAll checks for cancellation between iterations, even when the in-flight fetch ignores the signal.
Show answer
Mock fetch so it resolves to { ok: true, json: async () => ({}) } and aborts the controller inside the mock on the first call. Then await assert.rejects(fetchAll(['/a', '/b'], { signal }), { name: 'AbortError' }) and assert that the mock was called exactly once. The first request completes, and throwIfAborted() stops the loop before /b.
Exercise
Why does the success-path test compare the removed listener with the added one instead of only checking that removeEventListener was called once?
Show answer
removeEventListener silently does nothing when given a different function from the one registered. Code that calls it with a new arrow function would pass a call-count check but still leak the original listener. Comparing references proves the listener was actually detached.