Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

fetch-failure.test.ts

86 lines2.5 KB

1import { afterEach, describe, expect, it, vi } from 'vitest'
2​
3import { fetchJson, fetchText } 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 )
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})