File size: 1,144 Bytes
45a105b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import { describe, it, expect, vi, beforeEach } from 'vitest'
import { apiRequest, ApiRequestError, getLastRequestId } from './client'
describe('api client', () => {
beforeEach(() => vi.restoreAllMocks())
it('captures X-Request-ID and parses JSON', async () => {
globalThis.fetch = vi.fn().mockResolvedValue(
new Response(JSON.stringify({ ok: true }), { status: 200, headers: { 'x-request-id': 'req-123' } }),
) as any
const r = await apiRequest<{ ok: boolean }>('/x')
expect(r.ok).toBe(true)
expect(getLastRequestId()).toBe('req-123')
})
it('throws typed error with detail + requestId on 4xx', async () => {
globalThis.fetch = vi.fn().mockResolvedValue(
new Response(JSON.stringify({ detail: 'bad' }), { status: 422, headers: { 'x-request-id': 'req-9' } }),
) as any
await expect(apiRequest('/x')).rejects.toMatchObject({ status: 422, message: 'bad', requestId: 'req-9' })
})
it('wraps network errors safely', async () => {
globalThis.fetch = vi.fn().mockRejectedValue(new TypeError('fail')) as any
await expect(apiRequest('/x')).rejects.toBeInstanceOf(ApiRequestError)
})
})
|