|
| 1 | +import { describe, expect, it, vi } from "vitest"; |
| 2 | +import { createDiscordRequestClient, DISCORD_REST_TIMEOUT_MS } from "./proxy-request-client.js"; |
| 3 | + |
| 4 | +describe("createDiscordRequestClient", () => { |
| 5 | + it("injects an abort timeout signal into fetch calls", async () => { |
| 6 | + const fetchSpy = vi.fn(async (_input: string | URL | Request, init?: RequestInit) => { |
| 7 | + expect(init?.signal).toBeDefined(); |
| 8 | + expect(init!.signal!.aborted).toBe(false); |
| 9 | + return new Response(JSON.stringify([]), { status: 200 }); |
| 10 | + }); |
| 11 | + |
| 12 | + const client = createDiscordRequestClient("Bot test-token", { |
| 13 | + fetch: fetchSpy as never, |
| 14 | + queueRequests: false, |
| 15 | + }); |
| 16 | + |
| 17 | + await client.get("/channels/123/messages"); |
| 18 | + expect(fetchSpy).toHaveBeenCalledTimes(1); |
| 19 | + }); |
| 20 | + |
| 21 | + it( |
| 22 | + "aborts hanging requests after the timeout", |
| 23 | + async () => { |
| 24 | + const fetchSpy = vi.fn( |
| 25 | + (_input: string | URL | Request, init?: RequestInit) => |
| 26 | + new Promise<Response>((_resolve, reject) => { |
| 27 | + init?.signal?.addEventListener("abort", () => { |
| 28 | + reject(new DOMException("The operation was aborted.", "AbortError")); |
| 29 | + }); |
| 30 | + }), |
| 31 | + ); |
| 32 | + |
| 33 | + const client = createDiscordRequestClient("Bot test-token", { |
| 34 | + fetch: fetchSpy as never, |
| 35 | + queueRequests: false, |
| 36 | + }); |
| 37 | + |
| 38 | + await expect(client.get("/channels/123/messages")).rejects.toThrow(); |
| 39 | + }, |
| 40 | + DISCORD_REST_TIMEOUT_MS + 5_000, |
| 41 | + ); |
| 42 | + |
| 43 | + it("always injects a timeout signal even without a caller signal", async () => { |
| 44 | + let receivedSignal: AbortSignal | undefined; |
| 45 | + |
| 46 | + const fetchSpy = vi.fn(async (_input: string | URL | Request, init?: RequestInit) => { |
| 47 | + receivedSignal = init?.signal ?? undefined; |
| 48 | + return new Response(JSON.stringify({}), { status: 200 }); |
| 49 | + }); |
| 50 | + |
| 51 | + const client = createDiscordRequestClient("Bot test-token", { |
| 52 | + fetch: fetchSpy as never, |
| 53 | + queueRequests: false, |
| 54 | + }); |
| 55 | + |
| 56 | + await client.get("/channels/123/messages"); |
| 57 | + |
| 58 | + expect(receivedSignal).toBeDefined(); |
| 59 | + expect(receivedSignal!.aborted).toBe(false); |
| 60 | + }); |
| 61 | + |
| 62 | + it("exports a reasonable timeout constant", () => { |
| 63 | + expect(DISCORD_REST_TIMEOUT_MS).toBeGreaterThanOrEqual(5_000); |
| 64 | + expect(DISCORD_REST_TIMEOUT_MS).toBeLessThanOrEqual(30_000); |
| 65 | + }); |
| 66 | +}); |
0 commit comments