Open History to see the last commit
1import { afterEach, describe, expect, it, vi } from 'vitest'
2
3import { fetchJson, fetchText, timeoutSignal } from './types.ts'
4
5const LISTING_URL = 'https://api.example.com/v1/models'
6
7afterEach(() => {
8 vi.unstubAllGlobals()
9})
10
11function respondWith(body: string, status: number, statusText: string) {
12 vi.stubGlobal(
13 'fetch',
14 vi.fn(() => Promise.resolve(new Response(body, { status, statusText }))),
15 )
16}
17
18describe('fetch failure message', () => {
19 it("quotes the provider's stated reason after the status", async () => {
20 // Illustrative Gemini error shape, not a recorded response.
21 respondWith(
22 JSON.stringify({
23 error: {
24 code: 400,
25 message: 'User location is not supported for the API use.',
26 status: 'FAILED_PRECONDITION',
27 },
28 }),
29 400,
30 'Bad Request',
31 )
32
33 await expect(fetchJson(LISTING_URL)).rejects.toThrow(
34 `fetch failed: ${LISTING_URL} → 400 Bad Request: {"error":{"code":400,"message":"User location is not supported for the API use."`,
35 )
36 })
37
38 it('collapses whitespace and cuts a long body at 200 characters', async () => {
39 respondWith(`<html>\n <body>${'x'.repeat(500)}</body>`, 503, 'Unavailable')
40
41 const message = await fetchText(LISTING_URL).then(
42 () => '',
43 (err: unknown) => (err as Error).message,
44 )
45
46 const snippet = message.split('→ 503 Unavailable: ')[1] ?? ''
47 expect(snippet.startsWith('<html> <body>xxx')).toBe(true)
48 expect(snippet).toHaveLength(201)
49 expect(snippet.endsWith('…')).toBe(true)
50 })
51
52 it('ends at the status when the body is empty', async () => {
53 respondWith('', 403, 'Forbidden')
54
55 await expect(fetchJson(LISTING_URL)).rejects.toThrow(
56 new Error(`fetch failed: ${LISTING_URL} → 403 Forbidden`),
57 )
58 })
59
60 it('throws with what arrived when the error body stalls', async () => {
61 vi.useFakeTimers()
62 const body = new ReadableStream<Uint8Array>({
63 start(controller) {
64 controller.enqueue(new TextEncoder().encode('upstream stalled'))
65 },
66 })
67 vi.stubGlobal(
68 'fetch',
69 vi.fn(() =>
70 Promise.resolve(
71 new Response(body, { status: 502, statusText: 'Bad Gateway' }),
72 ),
73 ),
74 )
75
76 const failed = fetchJson(LISTING_URL).catch((err: unknown) => err)
77 await vi.advanceTimersByTimeAsync(2000)
78 vi.useRealTimers()
79
80 expect(await failed).toEqual(
81 new Error(
82 `fetch failed: ${LISTING_URL} → 502 Bad Gateway: upstream stalled`,
83 ),
84 )
85 })
86
87 it('names the url and the timeout budget when the fetch aborts', async () => {
88 const timeout = new DOMException(
89 'The operation was aborted due to timeout',
90 'TimeoutError',
91 )
92 const fetcher = () => Promise.reject(timeout)
93
94 await expect(
95 fetchText(LISTING_URL, { signal: timeoutSignal(20_000) }, fetcher),
96 ).rejects.toThrow(`fetch failed: ${LISTING_URL} → timeout after 20000ms`)
97 await expect(fetchJson(LISTING_URL, undefined, fetcher)).rejects.toThrow(
98 `fetch failed: ${LISTING_URL} → timeout`,
99 )
100 })
101
102 it('names the url and the timeout budget when the body read aborts', async () => {
103 const timeout = new DOMException(
104 'The operation was aborted due to timeout',
105 'TimeoutError',
106 )
107 const stalled = () =>
108 new Response(
109 new ReadableStream<Uint8Array>({
110 pull(controller) {
111 controller.error(timeout)
112 },
113 }),
114 { status: 200, statusText: 'OK' },
115 )
116 vi.stubGlobal(
117 'fetch',
118 vi.fn(() => Promise.resolve(stalled())),
119 )
120
121 await expect(
122 fetchText(LISTING_URL, { signal: timeoutSignal(20_000) }),
123 ).rejects.toThrow(`fetch failed: ${LISTING_URL} → timeout after 20000ms`)
124 await expect(fetchJson(LISTING_URL)).rejects.toThrow(
125 `fetch failed: ${LISTING_URL} → timeout`,
126 )
127 })
128
129 it('leaves a non-timeout rejection unchanged', async () => {
130 const fetcher = () => Promise.reject(new TypeError('getaddrinfo ENOTFOUND'))
131
132 await expect(fetchText(LISTING_URL, undefined, fetcher)).rejects.toThrow(
133 'getaddrinfo ENOTFOUND',
134 )
135 })
136})