Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions test/_fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ export const fixture: (
opts?: Partial<ServerOptions>,
_Response?: typeof globalThis.Response,
) => ServerOptions = (opts, _Response = globalThis.Response) => {
let abortCount = 0;
const aborts: Array<{
request: string; // example: GET /test
reason: string;
}> = [];

return {
...opts,
Expand Down Expand Up @@ -46,6 +49,14 @@ export const fixture: (

async fetch(req) {
const url = new URL(req.url);

req.signal.addEventListener("abort", () => {
aborts.push({
request: `${req.method} ${url.pathname}`,
reason: req.signal.reason.toString(),
});
});

switch (url.pathname) {
case "/": {
return new _Response("ok");
Expand Down Expand Up @@ -161,9 +172,6 @@ export const fixture: (
return res.clone();
}
case "/abort": {
req.signal.addEventListener("abort", () => {
abortCount++;
});
return new _Response(
new ReadableStream({
async start(controller) {
Expand All @@ -183,8 +191,8 @@ export const fixture: (
},
);
}
case "/abort-count": {
return _Response.json({ abortCount });
case "/abort-log": {
return _Response.json(aborts);
}
}
return new _Response("404", { status: 404 });
Expand Down
29 changes: 24 additions & 5 deletions test/_tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,13 @@ export function addTests(opts: {
runtime: string;
fetch?: typeof globalThis.fetch;
}): void {
const { url, fetch = globalThis.fetch } = opts;
const { url, fetch: _fetch = globalThis.fetch } = opts;

let fetchCount = 0;
const fetch = (...args: Parameters<typeof _fetch>) => {
fetchCount++;
return _fetch(...args);
};

test("GET works", async () => {
const response = await fetch(url("/"));
Expand Down Expand Up @@ -112,10 +118,23 @@ export function addTests(opts: {
await new Promise((resolve) => setTimeout(resolve, 100));
}

const { abortCount } = await fetch(url("/abort-count")).then((res) =>
res.json(),
);
expect(abortCount).toBe(1);
const aborts = await fetch(url("/abort-log")).then((res) => res.json());
const abort = aborts.find((a: any) => a.request === "GET /abort");
expect(abort).toBeDefined();
expect(abort.reason).toMatch(/AbortError:/);
});

test("total aborts", async () => {
let expectedAbortCount = fetchCount;
if (opts.runtime === "bun") {
expectedAbortCount = 1; // Bun only aborts explicitly
}

const res = await fetch(url("/abort-log"));
expect(res.status).toBe(200);
const aborts = await res.json();
// console.log(aborts.map((a: any) => `${a.request}`).join("\n"));
expect(aborts.length).toBe(expectedAbortCount);
});

describe("plugin", () => {
Expand Down