sonda/web/src/api/client.test.ts

157 lines
6.5 KiB
TypeScript

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<string, string>).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', { email: 'a@example.org', 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<string, string>)['Content-Type']).toBe('application/json')
expect(JSON.parse(calls[0].init.body as string)).toEqual({ track_id: 3 })
})
test('keepalive lets a request outlive the page', async () => {
const { calls } = mockFetch({ 'POST /api/v1/listens': () => ({ status: 'recorded' }) })
await api.post('/listens', { track_id: 3 }, { keepalive: true })
expect(calls[0].init.keepalive).toBe(true)
})
test('a request without keepalive does not ask for it', async () => {
const { calls } = mockFetch({ 'POST /api/v1/listens': () => ({ status: 'recorded' }) })
await api.post('/listens', { track_id: 3 })
expect(calls[0].init.keepalive).toBeUndefined()
})
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' })
})
test('a list value is sent once for each item', async () => {
const { calls } = mockFetch({ 'GET /api/v1/discover': () => ({}) })
await api.get('/discover', { seed: [3, 5], limit: 10 })
expect(calls[0].url.searchParams.getAll('seed')).toEqual(['3', '5'])
expect(calls[0].url.searchParams.get('limit')).toBe('10')
})
test('a signal is given to the request', async () => {
const { calls } = mockFetch({ 'GET /api/v1/discover': () => ({}) })
const controller = new AbortController()
await api.get('/discover', undefined, { signal: controller.signal })
expect(calls[0].init.signal).toBe(controller.signal)
})
test('a cancelled request is not reported as a network failure', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => {
throw new DOMException('aborted', 'AbortError')
}),
)
const failure = await api.get('/discover').catch((e: unknown) => e)
expect(failure).not.toBeInstanceOf(ApiError)
expect(failure).toMatchObject({ name: 'AbortError' })
})
test('Retry-After on an error is kept in seconds', async () => {
mockFetch({
'GET /api/v1/discover': () =>
new Response(JSON.stringify({ error: { code: 'discover_busy', message: 'busy' } }), {
status: 429,
headers: { 'Content-Type': 'application/json', 'Retry-After': '12' },
}),
})
const failure = await api.get('/discover').catch((e: unknown) => e)
expect(failure).toMatchObject({ status: 429, code: 'discover_busy', retryAfter: 12 })
})
test('an error without Retry-After has none', async () => {
mockFetch({ 'GET /api/v1/artists': () => apiError(400, 'invalid_input') })
const failure = (await api.get('/artists').catch((e: unknown) => e)) as ApiError
expect(failure.retryAfter).toBeUndefined()
})