/** * Unit tests for the admin API client (URL/parameter building, methods, * response parsing, error propagation). */ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { adminCreateArticle, adminDeleteArticle, adminGetArticle, adminListArticles, adminListAuthors, adminListCategories, adminUpdateArticle, } from '../../api/admin'; import { ApiError, TOKEN_KEY } from '../../api/client'; import type { AdminArticlesPage } from '../../types/admin'; const SAMPLE_PAGE: AdminArticlesPage = { articles: [ { id: 1, title: 'First story', content: '

Hello

', author_id: 7, category_id: 1, author: { id: 7, name: 'Ada Lovelace', email: 'ada@example.com' }, category: { id: 1, name: 'Technology', slug: 'technology' }, published: true, created_at: '2024-05-01T12:00:00Z', }, ], total: 1, page: 1, page_size: 20, total_pages: 1, }; 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('admin API client', () => { let fetchMock: ReturnType; beforeEach(() => { localStorage.clear(); fetchMock = vi.fn(); vi.stubGlobal('fetch', fetchMock); }); it('listArticles builds the query string from all parameters', async () => { localStorage.setItem(TOKEN_KEY, 'admin-token'); fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE)); const res = await adminListArticles({ page: 2, pageSize: 50, search: ' breaking news ', sortBy: 'title', sortOrder: 'asc', }); expect(res).toEqual(SAMPLE_PAGE); const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]; // URLSearchParams encodes spaces as `+`. expect(url).toBe( '/api/v1/admin/articles?page=2&page_size=50&search=breaking+news&sort_by=title&sort_order=asc', ); expect(init.method).toBeUndefined(); // The JWT is attached as a Bearer token. expect((init.headers as Record).Authorization).toBe( 'Bearer admin-token', ); }); it('listArticles omits the search parameter when empty', async () => { fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE)); await adminListArticles({ page: 1, pageSize: 20, search: ' ', sortBy: 'created_at', sortOrder: 'desc', }); const [url] = fetchMock.mock.calls[0] as [string, RequestInit]; expect(url).toBe( '/api/v1/admin/articles?page=1&page_size=20&sort_by=created_at&sort_order=desc', ); }); it('getArticle requests the article by id', async () => { fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE.articles[0])); await adminGetArticle(7); const [url] = fetchMock.mock.calls[0] as [string, RequestInit]; expect(url).toBe('/api/v1/admin/articles/7'); }); it('createArticle POSTs the payload', async () => { fetchMock.mockResolvedValue(jsonResponse(201, SAMPLE_PAGE.articles[0])); await adminCreateArticle({ title: 'New story', content: '

Body

', author_id: 7, category_id: 2, published: false, }); const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]; expect(url).toBe('/api/v1/admin/articles'); expect(init.method).toBe('POST'); expect(JSON.parse(init.body as string)).toEqual({ title: 'New story', content: '

Body

', author_id: 7, category_id: 2, published: false, }); }); it('updateArticle PUTs the payload to the article route', async () => { fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE.articles[0])); await adminUpdateArticle(7, { title: 'Updated', content: '

Body

', author_id: 8, category_id: 1, published: true, }); const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]; expect(url).toBe('/api/v1/admin/articles/7'); expect(init.method).toBe('PUT'); }); it('deleteArticle sends DELETE and resolves to undefined on 204', async () => { fetchMock.mockResolvedValue({ ok: true, status: 204, statusText: 'No Content', } as Response); await expect(adminDeleteArticle(7)).resolves.toBeUndefined(); const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]; expect(url).toBe('/api/v1/admin/articles/7'); expect(init.method).toBe('DELETE'); }); it('listAuthors requests the author reference list', async () => { const authors = [{ id: 1, name: 'Ada Lovelace', email: 'ada@example.com', bio: null }]; fetchMock.mockResolvedValue(jsonResponse(200, authors)); const res = await adminListAuthors(); expect(res).toEqual(authors); const [url] = fetchMock.mock.calls[0] as [string, RequestInit]; expect(url).toBe('/api/v1/admin/authors'); }); it('listCategories requests the category reference list', async () => { const categories = [{ id: 1, name: 'Technology', slug: 'technology' }]; fetchMock.mockResolvedValue(jsonResponse(200, categories)); const res = await adminListCategories(); expect(res).toEqual(categories); const [url] = fetchMock.mock.calls[0] as [string, RequestInit]; expect(url).toBe('/api/v1/admin/categories'); }); it('surfaces the backend error for non-admin access (403)', async () => { localStorage.setItem(TOKEN_KEY, 'non-admin-token'); fetchMock.mockResolvedValue( jsonResponse(403, { detail: 'Admin access required', code: 'forbidden' }), ); const err = await adminListArticles({ page: 1, pageSize: 20, search: '', sortBy: 'created_at', sortOrder: 'desc', }).catch((e: unknown) => e); expect(err).toBeInstanceOf(ApiError); expect((err as ApiError).status).toBe(403); expect((err as ApiError).code).toBe('forbidden'); expect((err as ApiError).message).toBe('Admin access required'); }); });