import { beforeEach, describe, expect, it, vi } from 'vitest' import { mockNuxtImport, registerEndpoint } from '@nuxt/test-utils/runtime' import { createError, defineEventHandler, getHeader, readBody, setResponseStatus } from 'h3' import { useApi } from '~/composables/useApi' const { navigateToMock } = vi.hoisted(() => ({ navigateToMock: vi.fn() })) mockNuxtImport('navigateTo', () => navigateToMock) // Each test registers its own endpoint, with an empty base URL (see vitest.config.ts) so requests hit it directly const respond = (path: string, status: number, body: unknown, method: 'GET' | 'POST' | 'DELETE' = 'GET') => registerEndpoint(path, { method, handler: defineEventHandler((event) => { setResponseStatus(event, status) return body }) }) describe('useApi', () => { beforeEach(() => { navigateToMock.mockReset() useCookie('authenticated').value = true }) it('returns the API response on success', async () => { respond('/api/test/ok', 200, { success: true, data: [1, 2] }) expect(await useApi().get('/api/test/ok')).toEqual({ success: true, data: [1, 2] }) }) it('JSON-encodes bare string bodies so quotes and backslashes survive', async () => { const password = 'pa"ss\\word' let received: unknown let contentType: string | undefined registerEndpoint('/api/test/echo', { method: 'POST', handler: defineEventHandler(async (event) => { contentType = getHeader(event, 'content-type') received = await readBody(event) return { success: true } }) }) await useApi().post('/api/test/echo', password) expect(contentType).toContain('application/json') expect(received).toBe(password) }) it('sends DELETE requests', async () => { respond('/api/test/delete', 200, { success: true, data: { id: 3 } }, 'DELETE') expect((await useApi().delete('/api/test/delete')).success).toBe(true) }) it('passes through the API error message for failed requests', async () => { respond('/api/test/bad', 400, { success: false, error: 'The code must be numeric.' }, 'POST') const result = await useApi().post('/api/test/bad', 'abcd') expect(result).toEqual({ success: false, error: 'The code must be numeric.' }) expect(navigateToMock).not.toHaveBeenCalled() }) it('does not treat a wrong-password 401 as an expired session', async () => { respond('/api/test/login', 401, { success: false, error: 'Incorrect password.' }, 'POST') const result = await useApi().post('/api/test/login', 'nope') expect(result.error).toBe('Incorrect password.') expect(navigateToMock).not.toHaveBeenCalled() expect(useCookie('authenticated').value).toBe(true) }) it('sends the user to the login page when the session has expired (empty 401)', async () => { registerEndpoint('/api/test/expired', () => { throw createError({ statusCode: 401, data: undefined }) }) const result = await useApi().get('/api/test/expired') expect(result.success).toBe(false) expect(result.error).toMatch(/session has expired/i) expect(navigateToMock).toHaveBeenCalledWith('/login') expect(useCookie('authenticated').value).toBe(false) }) it('surfaces rate limiting (429) messages', async () => { respond('/api/test/limited', 429, { success: false, error: 'Too many login attempts.' }, 'POST') expect((await useApi().post('/api/test/limited', 'x')).error).toBe('Too many login attempts.') }) it('falls back to a generic message when the server cannot be reached', async () => { // Nothing is registered at this path and the request is aborted by the network layer const result = await useApi().get('http://127.0.0.1:1/unreachable') expect(result).toEqual({ success: false, error: 'Unable to reach the server.' }) expect(navigateToMock).not.toHaveBeenCalled() }) })