/** * Unit tests for the auth methods of the API client (token attachment, * 401 handling, request/response shapes). */ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { ApiError, login, logout, me, register, TOKEN_KEY } from '../api/client'; /** Minimal fetch Response look-alike for the client. */ function jsonResponse(status: number, body: unknown) { return { ok: status >= 200 && status < 300, status, statusText: 'OK', json: async () => body, text: async () => JSON.stringify(body), } as Response; } describe('auth API client', () => { let fetchMock: ReturnType; beforeEach(() => { localStorage.clear(); fetchMock = vi.fn(); vi.stubGlobal('fetch', fetchMock); }); it('login posts credentials to /auth/login and returns the token payload', async () => { fetchMock.mockResolvedValue(jsonResponse(200, { token: 'tok', username: 'alice' })); const res = await login('alice', 'password123'); expect(res).toEqual({ token: 'tok', username: 'alice' }); const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]; expect(url).toBe('/api/v1/auth/login'); expect(init.method).toBe('POST'); expect(JSON.parse(init.body as string)).toEqual({ username: 'alice', password: 'password123', }); }); it('register posts to /auth/register', async () => { fetchMock.mockResolvedValue(jsonResponse(201, { token: 'tok', username: 'bob' })); await register('bob', 'password123'); const [url] = fetchMock.mock.calls[0] as [string, RequestInit]; expect(url).toBe('/api/v1/auth/register'); }); it('attaches the stored token as a Bearer Authorization header', async () => { localStorage.setItem(TOKEN_KEY, 'stored-token'); fetchMock.mockResolvedValue(jsonResponse(200, { username: 'alice' })); await me(); const [, init] = fetchMock.mock.calls[0] as [string, RequestInit]; expect((init.headers as Record).Authorization).toBe( 'Bearer stored-token', ); }); it('sends no Authorization header without a stored token', async () => { fetchMock.mockResolvedValue(jsonResponse(200, { username: 'alice' })); await me(); const [, init] = fetchMock.mock.calls[0] as [string, RequestInit]; expect((init.headers as Record).Authorization).toBeUndefined(); }); it('me() prefers an explicit token over the stored one', async () => { localStorage.setItem(TOKEN_KEY, 'stored-token'); fetchMock.mockResolvedValue(jsonResponse(200, { username: 'alice' })); await me('explicit-token'); const [, init] = fetchMock.mock.calls[0] as [string, RequestInit]; expect((init.headers as Record).Authorization).toBe( 'Bearer explicit-token', ); }); it('drops the stored token on a 401 response', async () => { localStorage.setItem(TOKEN_KEY, 'dead-token'); fetchMock.mockResolvedValue( jsonResponse(401, { detail: 'Invalid or expired token', code: 'unauthorized' }), ); await expect(me('dead-token')).rejects.toBeInstanceOf(ApiError); expect(localStorage.getItem(TOKEN_KEY)).toBeNull(); }); it('surfaces the backend error detail for failed registrations', async () => { fetchMock.mockResolvedValue( jsonResponse(400, { detail: 'Username already exists', code: 'bad_request' }), ); const err = await register('alice', 'password123').catch((e: unknown) => e); expect(err).toBeInstanceOf(ApiError); expect((err as ApiError).status).toBe(400); expect((err as ApiError).code).toBe('bad_request'); expect((err as ApiError).message).toBe('Username already exists'); }); it('logout posts to /auth/logout and resolves to undefined', async () => { fetchMock.mockResolvedValue({ ok: true, status: 204, statusText: 'No Content', } as Response); await expect(logout()).resolves.toBeUndefined(); const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]; expect(url).toBe('/api/v1/auth/logout'); expect(init.method).toBe('POST'); expect(init.body).toBeUndefined(); }); });