Sub topic 16
Testing That Your Functions Really Cancel
This chapter assumes you know Node.js's built-in test runner (node:test) and node:assert, and that you have the cancellable delay() from earlier chapters. A cancellable function has more than one way to finish, and each one needs its own test. A happy-path test alone won't show that cancellation works.
What to test
A function that accepts a signal should behave correctly in each of these situations:
| Scenario | Expected behaviour |
|---|---|
| Signal already aborted | Rejects at once with `signal.reason` and does no work |
| Aborted while running | Rejects with `signal.reason` and stops its timer |
| Custom reason passed to `abort()` | Rejects with that exact value |
| Deadline signal fires | Rejects with a `TimeoutError` |
| Completes normally | Resolves and removes its abort listener |
A test file for delay()
Save this as delay.test.mjs and run it with node --test delay.test.mjs (Node 20 or later).
import { test } from 'node:test';
import assert from 'node:assert/strict';
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 });
});
}
test('rejects immediately when the signal is already aborted', async () => {
const start = Date.now();
await assert.rejects(
delay(10_000, { signal: AbortSignal.abort() }),
{ name: 'AbortError' }
);
assert.ok(Date.now() - start < 50);
});
test('rejects when aborted while running', async () => {
const controller = new AbortController();
const promise = delay(10_000, { signal: controller.signal });
controller.abort();
await assert.rejects(promise, { name: 'AbortError' });
});
test('passes a custom reason through unchanged', async () => {
const controller = new AbortController();
const reason = new Error('User navigated away');
const promise = delay(10_000, { signal: controller.signal });
controller.abort(reason);
await assert.rejects(promise, (err) => err === reason);
});
test('rejects with TimeoutError when a deadline expires', async () => {
await assert.rejects(
delay(10_000, { signal: AbortSignal.timeout(20) }),
{ name: 'TimeoutError' }
);
});
test('removes its abort listener after finishing normally', async () => {
const { signal } = new AbortController();
const removed = [];
const original = signal.removeEventListener.bind(signal);
signal.removeEventListener = (type, listener, options) => {
removed.push(type);
return original(type, listener, options);
};
await delay(10, { signal });
assert.deepEqual(removed, ['abort']);
});
test('works without a signal', async () => {
await delay(10);
});Why these tests catch real bugs
The aborted-while-running tests use a 10-second delay on purpose. If onAbort forgot to call clearTimeout, the promise would still reject, but the timer would keep the process alive. The test run would then take about ten seconds longer than it should. An unexpectedly slow test run usually means a timer or listener leaked.
The custom-reason test compares with === instead of checking name. That catches implementations that throw a new AbortError of their own and throw away the caller's reason.
Testing functions that forward signals
For a function such as fetchAll(), replace globalThis.fetch with a stub that records the signal it receives. Then assert that it is the same signal object you passed in, or that it aborts when yours does. That proves the signal reaches the nested call.
Exercise
A teammate's version of delay() passes every test above except "passes a custom reason through unchanged". What is the most likely bug in their onAbort handler?
Show answer
The handler rejects with a newly built error, such as new DOMException('Aborted', 'AbortError'), instead of signal.reason. That discards the custom reason the caller passed to abort(). The fix is to call reject(signal.reason).
Exercise
Why would a missing clearTimeout in onAbort make the test suite slower even though every assertion still passes?
Show answer
The promise still rejects, but the pending 10-second timer keeps the Node.js event loop alive. The test process can't exit until that timer fires.