import { beforeEach, expect, test, vi } from 'vitest' import { apiError, mockFetch } from '@/test/mockFetch' import { api, ApiError, setAuthHooks } from './client' const hooks = { getAccessToken: vi.fn(async () => 't1' as string | null), refresh: vi.fn(async () => 't2' as string | null), signOut: vi.fn(), } beforeEach(() => { hooks.getAccessToken.mockClear().mockResolvedValue('t1') hooks.refresh.mockClear().mockResolvedValue('t2') hooks.signOut.mockClear() setAuthHooks(hooks) }) function authorization(call: { init: RequestInit }): string | undefined { return (call.init.headers as Record).Authorization } test('sends the access token as a bearer token', async () => { const { calls } = mockFetch({ 'GET /api/v1/artists': () => ({ items: [] }) }) await api.get('/artists') expect(authorization(calls[0])).toBe('Bearer t1') }) test('an error response becomes an ApiError with the server code', async () => { mockFetch({ 'GET /api/v1/artists': () => apiError(400, 'invalid_input', 'bad limit') }) const failure = await api.get('/artists').catch((e: unknown) => e) expect(failure).toBeInstanceOf(ApiError) expect(failure).toMatchObject({ status: 400, code: 'invalid_input', message: 'bad limit' }) }) test('a 401 renews the session and retries once', async () => { let n = 0 const { calls } = mockFetch({ 'GET /api/v1/artists': () => (++n === 1 ? apiError(401, 'unauthorized') : { items: ['ok'] }), }) await expect(api.get('/artists')).resolves.toEqual({ items: ['ok'] }) expect(calls).toHaveLength(2) expect(hooks.refresh).toHaveBeenCalledTimes(1) expect(authorization(calls[1])).toBe('Bearer t2') expect(hooks.signOut).not.toHaveBeenCalled() }) test('a second 401 signs the user out and the error reaches the caller', async () => { const { calls } = mockFetch({ 'GET /api/v1/artists': () => apiError(401, 'unauthorized') }) await expect(api.get('/artists')).rejects.toMatchObject({ status: 401, code: 'unauthorized' }) expect(calls).toHaveLength(2) expect(hooks.signOut).toHaveBeenCalledTimes(1) }) test('a 401 with nothing to renew signs out without a retry', async () => { hooks.refresh.mockResolvedValue(null) const { calls } = mockFetch({ 'GET /api/v1/artists': () => apiError(401, 'unauthorized') }) await expect(api.get('/artists')).rejects.toMatchObject({ status: 401 }) expect(calls).toHaveLength(1) expect(hooks.signOut).toHaveBeenCalledTimes(1) }) test('a call that does not need a session sends no token and never renews', async () => { const { calls } = mockFetch({ 'POST /api/v1/auth/login': () => apiError(401, 'invalid_credentials') }) await expect(api.post('/auth/login', { username: 'a', password: 'b' }, { auth: false })).rejects.toMatchObject({ code: 'invalid_credentials', }) expect(hooks.getAccessToken).not.toHaveBeenCalled() expect(hooks.refresh).not.toHaveBeenCalled() expect(authorization(calls[0])).toBeUndefined() }) test('query values are sent, undefined ones are left out', async () => { const { calls } = mockFetch({ 'GET /api/v1/albums': () => ({ items: [] }) }) await api.get('/albums', { q: 'björk', limit: 50, artist_id: undefined, counted: true }) expect(calls[0].url.searchParams.get('q')).toBe('björk') expect(calls[0].url.searchParams.get('limit')).toBe('50') expect(calls[0].url.searchParams.has('artist_id')).toBe(false) expect(calls[0].url.searchParams.get('counted')).toBe('true') }) test('a JSON body is sent with its content type', async () => { const { calls } = mockFetch({ 'POST /api/v1/listens': () => ({ status: 'recorded' }) }) await api.post('/listens', { track_id: 3 }) expect((calls[0].init.headers as Record)['Content-Type']).toBe('application/json') expect(JSON.parse(calls[0].init.body as string)).toEqual({ track_id: 3 }) }) test('a 204 answer gives undefined', async () => { mockFetch({ 'POST /api/v1/auth/logout': () => new Response(null, { status: 204 }) }) await expect(api.post('/auth/logout', { refresh_token: 'r' }, { auth: false })).resolves.toBeUndefined() }) test('a network failure becomes an ApiError with the code network', async () => { vi.stubGlobal( 'fetch', vi.fn(async () => { throw new TypeError('Failed to fetch') }), ) await expect(api.get('/artists')).rejects.toMatchObject({ status: 0, code: 'network' }) })