Improve readability of test setup and assertions

This commit is contained in:
Matt Isenhower
2026-09-07 17:52:50 -07:00
parent 9971afe2e8
commit a1e934d0bd
27 changed files with 1223 additions and 245 deletions

View File

@@ -4,9 +4,15 @@ import { setTimeout as sleep } from 'node:timers/promises';
import { fetchWithTimeout } from '../src/common/fetch.js';
test('aborts a stalled request at its deadline', async () => {
mock.method(globalThis, 'fetch', (input, { signal }) => new Promise((resolve, reject) => {
signal.addEventListener('abort', () => reject(signal.reason), { once: true });
}));
mock.method(
globalThis,
'fetch',
(input, { signal }) =>
new Promise((resolve, reject) => {
signal.addEventListener('abort', () => reject(signal.reason), { once: true });
}),
);
try {
await Promise.all([
assert.rejects(fetchWithTimeout('https://example.test', {}, 5), { name: 'TimeoutError' }),
@@ -18,13 +24,24 @@ test('aborts a stalled request at its deadline', async () => {
});
test('keeps the deadline active while reading the response body', async () => {
mock.method(globalThis, 'fetch', async (input, { signal }) => new Response(new ReadableStream({
start(controller) {
signal.addEventListener('abort', () => controller.error(signal.reason), { once: true });
},
})));
mock.method(
globalThis,
'fetch',
async (input, { signal }) =>
new Response(
new ReadableStream({
start(controller) {
signal.addEventListener('abort', () => controller.error(signal.reason), {
once: true,
});
},
}),
),
);
try {
const response = await fetchWithTimeout('https://example.test', {}, 5);
await Promise.all([assert.rejects(response.text(), { name: 'TimeoutError' }), sleep(20)]);
} finally {
mock.restoreAll();
@@ -33,11 +50,19 @@ test('keeps the deadline active while reading the response body', async () => {
test('preserves caller cancellation', async () => {
let signal;
mock.method(globalThis, 'fetch', async (input, init) => { signal = init.signal; return new Response('ok'); });
mock.method(globalThis, 'fetch', async (input, init) => {
signal = init.signal;
return new Response('ok');
});
try {
const controller = new AbortController;
const controller = new AbortController();
await fetchWithTimeout('https://example.test', { signal: controller.signal });
controller.abort();
assert.equal(signal.aborted, true);
} finally {
mock.restoreAll();