import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { ApiError } from '@/api/client' import { resetAuth, useAuth } from '@/composables/useAuth' import { jsonResponse, mockFetch, USER } from './helpers' beforeEach(resetAuth) afterEach(() => vi.unstubAllGlobals()) describe('useAuth', () => { it("charge l'utilisateur connecté", async () => { mockFetch(jsonResponse(200, USER)) const { load, user, isAuthenticated } = useAuth() await load() expect(user.value).toEqual(USER) expect(isAuthenticated.value).toBe(true) }) it('considère un 403 comme « non connecté »', async () => { mockFetch(jsonResponse(403, { detail: 'Non authentifié.' })) const { load, isAuthenticated } = useAuth() await expect(load()).resolves.toBeNull() expect(isAuthenticated.value).toBe(false) }) it('propage les autres erreurs', async () => { mockFetch(jsonResponse(500, {})) await expect(useAuth().load()).rejects.toBeInstanceOf(ApiError) }) it("n'interroge l'API qu'une fois", async () => { const fetch = mockFetch(jsonResponse(200, USER)) const { load } = useAuth() await load() await load() expect(fetch).toHaveBeenCalledTimes(1) }) it("connecte puis recharge l'utilisateur (nouveau jeton CSRF)", async () => { const fetch = mockFetch( jsonResponse(200, { mfa_required: false, user: USER }), jsonResponse(200, USER), ) const { login, user } = useAuth() await login('medecin@exemple.be', 'secret') expect(user.value).toEqual(USER) expect(fetch.mock.calls.map(([url]) => url)).toEqual([ '/api/v1/auth/login/', '/api/v1/auth/me/', ]) }) it('déconnecte même si la requête échoue', async () => { mockFetch(jsonResponse(200, USER), jsonResponse(500, {}), jsonResponse(403, {})) const { load, logout, user } = useAuth() await load() await logout().catch(() => {}) expect(user.value).toBeNull() }) })