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) }) })