import { afterEach, describe, expect, it, vi } from 'vitest' import { api, ApiError, csrfToken } from '@/api/client' import { ASSESSMENT, jsonResponse, mockFetch } from './helpers' afterEach(() => { vi.unstubAllGlobals() document.cookie = 'csrftoken=; expires=Thu, 01 Jan 1970 00:00:00 GMT' }) describe('csrfToken', () => { it('lit le cookie csrftoken', () => { document.cookie = 'autre=1' document.cookie = 'csrftoken=abc123' expect(csrfToken()).toBe('abc123') }) it('renvoie une chaîne vide sans cookie', () => { expect(csrfToken()).toBe('') }) }) describe('api', () => { it('envoie le jeton CSRF et le corps JSON sur un POST', async () => { document.cookie = 'csrftoken=jeton' const fetch = mockFetch(jsonResponse(200, ASSESSMENT)) const result = await api.assess('Place de l’Université 1') expect(result).toEqual(ASSESSMENT) const [url, init] = fetch.mock.calls[0]! expect(url).toBe('/api/v1/assessments/') expect(init?.method).toBe('POST') expect(init?.credentials).toBe('same-origin') expect(init?.headers).toMatchObject({ 'X-CSRFToken': 'jeton', 'Content-Type': 'application/json', }) expect(JSON.parse(init?.body as string)).toEqual({ address: 'Place de l’Université 1' }) }) it("n'envoie pas de jeton CSRF sur un GET", async () => { const fetch = mockFetch(jsonResponse(200, {})) await api.me() expect(fetch.mock.calls[0]![1]?.headers).not.toHaveProperty('X-CSRFToken') }) it('accepte une réponse 204 sans corps', async () => { mockFetch(new Response(null, { status: 204 })) await expect(api.logout()).resolves.toBeUndefined() }) it('lève une ApiError avec le statut, le message et le code', async () => { mockFetch(jsonResponse(404, { code: 'address_not_found', detail: 'Adresse introuvable.' })) const error = await api.assess('nulle part').catch((e) => e) expect(error).toBeInstanceOf(ApiError) expect(error.status).toBe(404) expect(error.code).toBe('address_not_found') expect(error.message).toBe('Adresse introuvable.') }) it('gère une erreur sans corps JSON', async () => { mockFetch(new Response('403', { status: 403 })) const error = await api.me().catch((e) => e) expect(error).toBeInstanceOf(ApiError) expect(error.message).toBe('HTTP 403') expect(error.code).toBeUndefined() }) })