feat(admin): rebuild admin area around the Article domain

The admin area was managing a Hacker News-style Item model that the
public site never consumed, so the homepage always fell back to sample
data. Rebuild the admin area around the real public content model.

Backend:
- Remove the Item model, schema and admin API
- Admin API now manages articles at /api/v1/admin/articles (CRUD) with
  /api/v1/admin/authors and /api/v1/admin/categories reference data
- Add public read-only article endpoints (/api/v1/articles,
  /api/v1/articles/{id}): no auth, published-only, newest-first
- Rewrite Article schemas; ArticleRead embeds author and category
- Add idempotent seed_content.py dev seeder (3 authors, 4 categories,
  6 published articles)

Frontend:
- Admin UI rewritten around articles: AdminDashboard list, new
  EditArticlePage (create/edit, author/category selects, published
  toggle, Lexical editor, debounced auto-save)
- Replace AdminItem types and api client with the article domain
- Update App routes, AdminLayout sidebar, DeleteConfirmation, Lexical
  editor labels and Home/client comments to article terminology

Tests:
- Rewrite admin unit tests and the Playwright admin e2e spec for the
  article domain; add test_articles.py for the public endpoints and
  seeder
This commit is contained in:
Daniel Samson committed 2026-10-31 18:31:05 +00:00
1 parent de96d0b152
commit afa399776f
29 files changed
+2465 -1658

No files matched your search

+69 -43
View File
@@ -4,24 +4,28 @@
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
adminCreateItem,
adminDeleteItem,
adminGetItem,
adminListItems,
adminUpdateItem,
adminCreateArticle,
adminDeleteArticle,
adminGetArticle,
adminListArticles,
adminListAuthors,
adminListCategories,
adminUpdateArticle,
} from '../../api/admin';
import { ApiError, TOKEN_KEY } from '../../api/client';
import type { AdminItemsPage } from '../../types/admin';
import type { AdminArticlesPage } from '../../types/admin';
const SAMPLE_PAGE: AdminItemsPage = {
items: [
const SAMPLE_PAGE: AdminArticlesPage = {
articles: [
{
id: 1,
title: 'First story',
url: 'https://example.com/first',
points: 3,
username: 'alice',
content: '<p>Hello</p>',
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',
},
],
@@ -50,11 +54,11 @@ describe('admin API client', () => {
vi.stubGlobal('fetch', fetchMock);
});
it('listItems builds the query string from all parameters', async () => {
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 adminListItems({
const res = await adminListArticles({
page: 2,
pageSize: 50,
search: ' breaking news ',
@@ -66,7 +70,7 @@ describe('admin API client', () => {
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
// URLSearchParams encodes spaces as `+`.
expect(url).toBe(
'/api/v1/admin/items?page=2&page_size=50&search=breaking+news&sort_by=title&sort_order=asc',
'/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.
@@ -75,10 +79,10 @@ describe('admin API client', () => {
);
});
it('listItems omits the search parameter when empty', async () => {
it('listArticles omits the search parameter when empty', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE));
await adminListItems({
await adminListArticles({
page: 1,
pageSize: 20,
search: ' ',
@@ -88,79 +92,101 @@ describe('admin API client', () => {
const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(url).toBe(
'/api/v1/admin/items?page=1&page_size=20&sort_by=created_at&sort_order=desc',
'/api/v1/admin/articles?page=1&page_size=20&sort_by=created_at&sort_order=desc',
);
});
it('getItem requests the item by id', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE.items[0]));
it('getArticle requests the article by id', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE.articles[0]));
await adminGetItem(7);
await adminGetArticle(7);
const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(url).toBe('/api/v1/admin/items/7');
expect(url).toBe('/api/v1/admin/articles/7');
});
it('createItem POSTs the payload', async () => {
fetchMock.mockResolvedValue(jsonResponse(201, SAMPLE_PAGE.items[0]));
it('createArticle POSTs the payload', async () => {
fetchMock.mockResolvedValue(jsonResponse(201, SAMPLE_PAGE.articles[0]));
await adminCreateItem({
await adminCreateArticle({
title: 'New story',
url: '',
points: 0,
username: 'root',
content: '<p>Body</p>',
author_id: 7,
category_id: 2,
published: false,
});
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(url).toBe('/api/v1/admin/items');
expect(url).toBe('/api/v1/admin/articles');
expect(init.method).toBe('POST');
expect(JSON.parse(init.body as string)).toEqual({
title: 'New story',
url: '',
points: 0,
username: 'root',
content: '<p>Body</p>',
author_id: 7,
category_id: 2,
published: false,
});
});
it('updateItem PUTs the payload to the item route', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE.items[0]));
it('updateArticle PUTs the payload to the article route', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE.articles[0]));
await adminUpdateItem(7, {
await adminUpdateArticle(7, {
title: 'Updated',
url: 'https://example.com/new',
points: 9,
username: 'root',
content: '',
content: '<p>Body</p>',
author_id: 8,
category_id: 1,
published: true,
});
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(url).toBe('/api/v1/admin/items/7');
expect(url).toBe('/api/v1/admin/articles/7');
expect(init.method).toBe('PUT');
});
it('deleteItem sends DELETE and resolves to undefined on 204', async () => {
it('deleteArticle sends DELETE and resolves to undefined on 204', async () => {
fetchMock.mockResolvedValue({
ok: true,
status: 204,
statusText: 'No Content',
} as Response);
await expect(adminDeleteItem(7)).resolves.toBeUndefined();
await expect(adminDeleteArticle(7)).resolves.toBeUndefined();
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(url).toBe('/api/v1/admin/items/7');
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 adminListItems({
const err = await adminListArticles({
page: 1,
pageSize: 20,
search: '',
@@ -6,33 +6,49 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
adminDeleteItem,
adminListItems,
adminDeleteArticle,
adminListArticles,
} from '../../api/admin';
import { AdminDashboard } from '../../pages/AdminDashboard';
import type { AdminItemsPage } from '../../types/admin';
import type { AdminArticlesPage } from '../../types/admin';
vi.mock('../../api/admin', () => ({
adminListItems: vi.fn(),
adminGetItem: vi.fn(),
adminCreateItem: vi.fn(),
adminUpdateItem: vi.fn(),
adminDeleteItem: vi.fn(),
adminListArticles: vi.fn(),
adminGetArticle: vi.fn(),
adminCreateArticle: vi.fn(),
adminUpdateArticle: vi.fn(),
adminDeleteArticle: vi.fn(),
adminListAuthors: vi.fn(),
adminListCategories: vi.fn(),
}));
const items = (count: number, offset = 0) =>
Array.from({ length: count }, (_, i) => ({
id: i + 1 + offset,
title: `Story ${i + 1 + offset}`,
url: `https://example.com/story-${i + 1 + offset}`,
points: i + offset,
username: 'alice',
content: `<p>Body ${i + 1 + offset}</p>`,
created_at: `2024-05-0${(i % 9) + 1}T12:00:00Z`,
}));
const AUTHORS = [
{ id: 1, name: 'Ada Lovelace', email: 'ada@example.com' },
{ id: 2, name: 'Grace Hopper', email: 'grace@example.com' },
];
const CATEGORIES = [
{ id: 1, name: 'Technology', slug: 'technology' },
{ id: 2, name: 'Science', slug: 'science' },
];
const page = (overrides: Partial<AdminItemsPage> = {}): AdminItemsPage => ({
items: items(3),
const article = (id: number, overrides: Record<string, unknown> = {}) => ({
id,
title: `Story ${id}`,
content: `<p>Body ${id}</p>`,
author_id: AUTHORS[(id - 1) % AUTHORS.length].id,
category_id: CATEGORIES[(id - 1) % CATEGORIES.length].id,
author: AUTHORS[(id - 1) % AUTHORS.length],
category: CATEGORIES[(id - 1) % CATEGORIES.length],
published: true,
created_at: `2024-05-0${(id % 9) + 1}T12:00:00Z`,
...overrides,
});
const articles = (count: number, offset = 0) =>
Array.from({ length: count }, (_, i) => article(i + 1 + offset));
const page = (overrides: Partial<AdminArticlesPage> = {}): AdminArticlesPage => ({
articles: articles(3),
total: 3,
page: 1,
page_size: 20,
@@ -47,7 +63,7 @@ function lastCallParams(): {
sortBy: string;
sortOrder: string;
} {
const calls = vi.mocked(adminListItems).mock.calls;
const calls = vi.mocked(adminListArticles).mock.calls;
const last = calls[calls.length - 1][0];
return {
page: last.page,
@@ -71,23 +87,27 @@ function renderDashboard() {
describe('AdminDashboard', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(adminListItems).mockResolvedValue(page());
vi.mocked(adminDeleteItem).mockResolvedValue(undefined);
vi.mocked(adminListArticles).mockResolvedValue(page());
vi.mocked(adminDeleteArticle).mockResolvedValue(undefined);
});
it('renders the fetched items with their details', async () => {
it('renders the fetched articles with their details', async () => {
renderDashboard();
expect(await screen.findByText('Story 1')).toBeInTheDocument();
expect(screen.getByText('Story 2')).toBeInTheDocument();
expect(screen.getByText('Story 3')).toBeInTheDocument();
// All three seed items belong to "alice".
expect(screen.getAllByText('alice').length).toBe(3);
expect(screen.getByText('https://example.com/story-1')).toBeInTheDocument();
// Each row shows its author and category.
expect(screen.getAllByText('Ada Lovelace').length).toBeGreaterThan(0);
expect(screen.getAllByText('Grace Hopper').length).toBeGreaterThan(0);
expect(screen.getAllByText('Technology').length).toBeGreaterThan(0);
expect(screen.getByText('Showing 1–3 of 3')).toBeInTheDocument();
// Published badges: one per row (the "Published" column header is a
// columnheader role, not a cell).
expect(screen.getAllByRole('cell', { name: 'Published' })).toHaveLength(3);
// Edit links point at the edit route.
const editLinks = screen.getAllByRole('link', { name: /edit/i });
expect(editLinks[0].getAttribute('href')).toBe('/admin/items/1/edit');
expect(editLinks[0].getAttribute('href')).toBe('/admin/articles/1/edit');
});
it('requests the initial page with the default parameters', async () => {
@@ -106,7 +126,7 @@ describe('AdminDashboard', () => {
renderDashboard();
await screen.findByText('Story 1');
fireEvent.change(screen.getByLabelText('Search items'), {
fireEvent.change(screen.getByLabelText('Search articles'), {
target: { value: 'breaking' },
});
@@ -134,13 +154,13 @@ describe('AdminDashboard', () => {
expect(lastCallParams().sortOrder).toBe('desc');
// Switching columns starts on ascending again.
fireEvent.click(screen.getByRole('button', { name: /sort by points/i }));
expect(lastCallParams().sortBy).toBe('points');
fireEvent.click(screen.getByRole('button', { name: /sort by creation date/i }));
expect(lastCallParams().sortBy).toBe('created_at');
expect(lastCallParams().sortOrder).toBe('asc');
});
it('navigates pages and changes the page size', async () => {
vi.mocked(adminListItems).mockResolvedValue(
vi.mocked(adminListArticles).mockResolvedValue(
page({ total: 45, page: 2, total_pages: 3 }),
);
renderDashboard();
@@ -160,23 +180,23 @@ describe('AdminDashboard', () => {
});
it('shows an empty state when nothing matches the search', async () => {
vi.mocked(adminListItems).mockResolvedValue(page({ items: [], total: 0 }));
vi.mocked(adminListArticles).mockResolvedValue(page({ articles: [], total: 0 }));
renderDashboard();
await screen.findByText(/no items yet/i);
await screen.findByText(/no articles yet/i);
});
it('shows the error state with a retry action', async () => {
vi.mocked(adminListItems).mockRejectedValue(new Error('boom'));
vi.mocked(adminListArticles).mockRejectedValue(new Error('boom'));
renderDashboard();
expect(await screen.findByRole('alert')).toHaveTextContent(/boom|went wrong/i);
screen.getByRole('button', { name: /retry/i }).click();
await waitFor(() =>
expect(vi.mocked(adminListItems).mock.calls.length).toBeGreaterThanOrEqual(2),
expect(vi.mocked(adminListArticles).mock.calls.length).toBeGreaterThanOrEqual(2),
);
});
it('deletes an item only after explicit confirmation', async () => {
it('deletes an article only after explicit confirmation', async () => {
renderDashboard();
await screen.findByText('Story 1');
@@ -184,30 +204,30 @@ describe('AdminDashboard', () => {
fireEvent.click(screen.getAllByRole('button', { name: /delete/i })[0]);
const dialog = await screen.findByRole('dialog');
expect(dialog).toHaveTextContent('Story 1');
expect(vi.mocked(adminDeleteItem)).not.toHaveBeenCalled();
expect(vi.mocked(adminDeleteArticle)).not.toHaveBeenCalled();
// Cancel: no API call.
fireEvent.click(screen.getByRole('button', { name: /cancel/i }));
expect(await screen.findByText('Story 1')).toBeInTheDocument();
expect(vi.mocked(adminDeleteItem)).not.toHaveBeenCalled();
expect(vi.mocked(adminDeleteArticle)).not.toHaveBeenCalled();
// Confirm: the API is called and the list refreshes.
const listCallsBefore = vi.mocked(adminListItems).mock.calls.length;
const listCallsBefore = vi.mocked(adminListArticles).mock.calls.length;
fireEvent.click(screen.getAllByRole('button', { name: /delete/i })[0]);
await screen.findByRole('dialog');
fireEvent.click(screen.getByRole('button', { name: /yes, delete/i }));
await waitFor(() =>
expect(vi.mocked(adminDeleteItem)).toHaveBeenCalledWith(1),
expect(vi.mocked(adminDeleteArticle)).toHaveBeenCalledWith(1),
);
expect(
vi.mocked(adminListItems).mock.calls.length,
vi.mocked(adminListArticles).mock.calls.length,
).toBeGreaterThanOrEqual(listCallsBefore + 1);
});
it('keeps the dialog open and shows the error when the delete fails', async () => {
vi.mocked(adminDeleteItem).mockRejectedValue(
new Error('Deleting the item failed.') as Error & { status?: number },
vi.mocked(adminDeleteArticle).mockRejectedValue(
new Error('Deleting the article failed.') as Error & { status?: number },
);
renderDashboard();
await screen.findByText('Story 1');
@@ -217,7 +237,7 @@ describe('AdminDashboard', () => {
fireEvent.click(screen.getByRole('button', { name: /yes, delete/i }));
const alert = await screen.findByRole('alert');
expect(alert).toHaveTextContent(/deleting the item failed/i);
expect(alert).toHaveTextContent(/deleting the article failed/i);
// Dialog still open.
expect(screen.getByRole('dialog')).toBeInTheDocument();
});
@@ -6,15 +6,17 @@
import { act, fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { DeleteConfirmation } from '../../components/DeleteConfirmation';
import type { AdminItem } from '../../types/admin';
import type { AdminArticle } from '../../types/admin';
const ITEM: AdminItem = {
const ARTICLE: AdminArticle = {
id: 42,
title: 'Breaking: the sky is falling',
url: 'https://example.com/sky',
points: 12,
username: 'alice',
content: '<p>…</p>',
author_id: 1,
category_id: 1,
author: { id: 1, name: 'Ada Lovelace', email: 'ada@example.com' },
category: { id: 1, name: 'Technology', slug: 'technology' },
published: true,
created_at: '2024-05-01T12:00:00Z',
};
@@ -23,7 +25,7 @@ function renderModal(props: Partial<Parameters<typeof DeleteConfirmation>[0]> =
const onCancel = vi.fn();
const utils = render(
<DeleteConfirmation
item={ITEM}
article={ARTICLE}
onConfirm={onConfirm}
onCancel={onCancel}
{...props}
@@ -33,7 +35,7 @@ function renderModal(props: Partial<Parameters<typeof DeleteConfirmation>[0]> =
}
describe('DeleteConfirmation', () => {
it('shows the warning layout with the item title', () => {
it('shows the warning layout with the article title', () => {
renderModal();
const dialog = screen.getByRole('dialog');
@@ -104,8 +106,8 @@ describe('DeleteConfirmation', () => {
});
it('renders an error message when provided', () => {
renderModal({ error: 'Deleting the item failed.' });
renderModal({ error: 'Deleting the article failed.' });
expect(screen.getByRole('alert')).toHaveTextContent('Deleting the item failed.');
expect(screen.getByRole('alert')).toHaveTextContent('Deleting the article failed.');
});
});
@@ -0,0 +1,289 @@
/**
* Tests for the EditArticlePage (M6): create/edit form validation,
* reference-list prefill in create mode, prefill in edit mode, save
* flows (success navigation + error display) and the load-failure view.
* The Lexical editor is stubbed; its HTML contract is exercised through
* the `editor-body` textarea.
*/
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
adminCreateArticle,
adminGetArticle,
adminListAuthors,
adminListCategories,
adminUpdateArticle,
} from '../../api/admin';
import { ApiError } from '../../api/client';
import { EditArticlePage as EditPage } from '../../pages/EditArticlePage';
import type { AdminArticle } from '../../types/admin';
vi.mock('../../api/admin', () => ({
adminListArticles: vi.fn(),
adminGetArticle: vi.fn(),
adminCreateArticle: vi.fn(),
adminUpdateArticle: vi.fn(),
adminDeleteArticle: vi.fn(),
adminListAuthors: vi.fn(),
adminListCategories: vi.fn(),
}));
vi.mock('../../components/LexicalEditor', () => ({
LexicalEditor: ({
initialHtml,
onChange,
}: {
initialHtml: string;
onChange: (html: string) => void;
placeholder?: string;
}) => (
<div data-testid="lexical-stub">
<textarea
data-testid="editor-body"
defaultValue={initialHtml}
aria-label="Article content"
onChange={(event) => onChange(event.target.value)}
/>
</div>
),
}));
const AUTHORS = [
{ id: 1, name: 'Ada Lovelace', email: 'ada@example.com' },
{ id: 2, name: 'Grace Hopper', email: 'grace@example.com' },
];
const CATEGORIES = [
{ id: 1, name: 'Technology', slug: 'technology' },
{ id: 2, name: 'Science', slug: 'science' },
];
const ARTICLE: AdminArticle = {
id: 5,
title: 'Original headline',
content: '<p>Original body</p>',
author_id: 2,
category_id: 1,
author: AUTHORS[1],
category: CATEGORIES[0],
published: true,
created_at: '2024-05-01T12:00:00Z',
};
function DashboardStub() {
const location = useLocation();
const notice = (location.state as { notice?: string } | null)?.notice ?? '';
return (
<div data-testid="dashboard-stub">
{notice && <p data-testid="dashboard-notice">{notice}</p>}
</div>
);
}
function renderAt(path: string) {
return render(
<MemoryRouter
initialEntries={[path]}
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
>
<Routes>
<Route path="/admin" element={<DashboardStub />} />
<Route path="/admin/articles/new" element={<EditPage />} />
<Route path="/admin/articles/:id/edit" element={<EditPage />} />
</Routes>
</MemoryRouter>,
);
}
describe('EditArticlePage (create)', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(adminListAuthors).mockResolvedValue(AUTHORS);
vi.mocked(adminListCategories).mockResolvedValue(CATEGORIES);
vi.mocked(adminCreateArticle).mockResolvedValue({ ...ARTICLE, id: 99 });
vi.mocked(adminUpdateArticle).mockResolvedValue(ARTICLE);
});
it('pre-fills the first author and category from the reference lists', async () => {
renderAt('/admin/articles/new');
await screen.findByTestId('lexical-stub');
await waitFor(() =>
expect(screen.getByLabelText(/^Author/)).toHaveValue('1'),
);
expect(screen.getByLabelText(/^Category/)).toHaveValue('1');
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('New article');
});
it('blocks submission with an empty title and does not call the API', async () => {
renderAt('/admin/articles/new');
await screen.findByTestId('lexical-stub');
await waitFor(() =>
expect(screen.getByLabelText(/^Author/)).toHaveValue('1'),
);
screen.getByRole('button', { name: /create article/i }).click();
// The field error and the form-level error are both alerts.
const alerts = await screen.findAllByRole('alert');
expect(
alerts.some((el) => /title is required/i.test(el.textContent ?? '')),
).toBe(true);
expect(vi.mocked(adminCreateArticle)).not.toHaveBeenCalled();
expect(screen.queryByTestId('dashboard-stub')).not.toBeInTheDocument();
});
it('blocks submission with an empty body', async () => {
renderAt('/admin/articles/new');
await screen.findByTestId('lexical-stub');
await waitFor(() =>
expect(screen.getByLabelText(/^Author/)).toHaveValue('1'),
);
fireEvent.change(screen.getByLabelText(/^Title/), { target: { value: 'Only a title' } });
screen.getByRole('button', { name: /create article/i }).click();
const alerts = await screen.findAllByRole('alert');
expect(
alerts.some((el) => /content is required/i.test(el.textContent ?? '')),
).toBe(true);
expect(vi.mocked(adminCreateArticle)).not.toHaveBeenCalled();
});
it('creates the article with trimmed values and navigates back with a notice', async () => {
renderAt('/admin/articles/new');
await screen.findByTestId('lexical-stub');
await waitFor(() =>
expect(screen.getByLabelText(/^Author/)).toHaveValue('1'),
);
fireEvent.change(screen.getByLabelText(/^Title/), {
target: { value: ' Fresh story ' },
});
fireEvent.change(screen.getByLabelText(/^Author/), { target: { value: '2' } });
fireEvent.change(screen.getByLabelText(/^Category/), { target: { value: '2' } });
fireEvent.click(screen.getByLabelText(/^Published/));
fireEvent.change(screen.getByTestId('editor-body'), {
target: { value: '<p>Body <strong>here</strong></p>' },
});
screen.getByRole('button', { name: /create article/i }).click();
await waitFor(() =>
expect(vi.mocked(adminCreateArticle)).toHaveBeenCalledWith({
title: 'Fresh story',
content: '<p>Body <strong>here</strong></p>',
author_id: 2,
category_id: 2,
published: true,
}),
);
expect(await screen.findByTestId('dashboard-stub')).toBeInTheDocument();
expect(screen.getByTestId('dashboard-notice')).toHaveTextContent(
'“Fresh story” was saved.',
);
});
it('disables the create button while the request is in flight', async () => {
let resolveCreate!: (value: AdminArticle) => void;
vi.mocked(adminCreateArticle).mockReturnValueOnce(
new Promise<AdminArticle>((resolve) => {
resolveCreate = resolve;
}),
);
renderAt('/admin/articles/new');
await screen.findByTestId('lexical-stub');
await waitFor(() =>
expect(screen.getByLabelText(/^Author/)).toHaveValue('1'),
);
fireEvent.change(screen.getByLabelText(/^Title/), { target: { value: 'Pending' } });
fireEvent.change(screen.getByTestId('editor-body'), {
target: { value: '<p>Body</p>' },
});
screen.getByRole('button', { name: /create article/i }).click();
const button = screen.getByRole('button', { name: /create article/i });
await waitFor(() => expect(button).toBeDisabled());
resolveCreate({ ...ARTICLE, id: 99, title: 'Pending' });
expect(await screen.findByTestId('dashboard-stub')).toBeInTheDocument();
});
it('shows the backend error when the create request fails', async () => {
vi.mocked(adminCreateArticle).mockRejectedValue(
new ApiError(422, 'Validation failed', 'validation_error'),
);
renderAt('/admin/articles/new');
await screen.findByTestId('lexical-stub');
await waitFor(() =>
expect(screen.getByLabelText(/^Author/)).toHaveValue('1'),
);
fireEvent.change(screen.getByLabelText(/^Title/), { target: { value: 'x' } });
fireEvent.change(screen.getByTestId('editor-body'), {
target: { value: '<p>Body</p>' },
});
screen.getByRole('button', { name: /create article/i }).click();
expect(await screen.findByRole('alert')).toHaveTextContent('Validation failed');
});
});
describe('EditArticlePage (edit)', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(adminListAuthors).mockResolvedValue(AUTHORS);
vi.mocked(adminListCategories).mockResolvedValue(CATEGORIES);
vi.mocked(adminGetArticle).mockResolvedValue(ARTICLE);
vi.mocked(adminUpdateArticle).mockResolvedValue(ARTICLE);
});
it('loads and pre-fills the article, then updates it on save', async () => {
renderAt('/admin/articles/5/edit');
// Loading state first.
expect(screen.getByRole('status')).toHaveTextContent(/loading article/i);
await screen.findByTestId('lexical-stub');
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent(
'Edit article #5',
);
expect(screen.getByLabelText(/^Title/)).toHaveValue('Original headline');
expect(screen.getByLabelText(/^Author/)).toHaveValue('2');
expect(screen.getByLabelText(/^Category/)).toHaveValue('1');
expect(screen.getByLabelText(/^Published/)).toBeChecked();
expect(screen.getByTestId('editor-body')).toHaveValue('<p>Original body</p>');
fireEvent.change(screen.getByLabelText(/^Title/), {
target: { value: 'Retitled' },
});
screen.getByRole('button', { name: /save changes/i }).click();
await waitFor(() =>
expect(vi.mocked(adminUpdateArticle)).toHaveBeenCalledWith(5, {
title: 'Retitled',
content: '<p>Original body</p>',
author_id: 2,
category_id: 1,
published: true,
}),
);
expect(await screen.findByTestId('dashboard-stub')).toBeInTheDocument();
});
it('shows the not-found view when the article cannot be loaded', async () => {
vi.mocked(adminGetArticle).mockRejectedValue(
new ApiError(404, 'Article not found', 'not_found'),
);
renderAt('/admin/articles/999/edit');
expect(await screen.findByRole('heading', { level: 1 })).toHaveTextContent(
/article not found/i,
);
expect(screen.getByRole('link', { name: /back to articles/i })).toHaveAttribute(
'href',
'/admin',
);
});
});
@@ -1,275 +0,0 @@
/**
* Tests for the EditItemPage (M6): create/edit form validation, prefill
* in edit mode, save flows (success navigation + error display) and the
* load-failure view. The Lexical editor is stubbed; its HTML contract
* is exercised through the `editor-body` textarea.
*/
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { Mock } from 'vitest';
import {
adminCreateItem,
adminGetItem,
adminUpdateItem,
} from '../../api/admin';
import { ApiError, TOKEN_KEY, me as clientMe } from '../../api/client';
import { AuthProvider } from '../../auth';
import { EditItemPage as EditPage } from '../../pages/EditItemPage';
import type { AdminItem } from '../../types/admin';
vi.mock('../../api/admin', () => ({
adminListItems: vi.fn(),
adminGetItem: vi.fn(),
adminCreateItem: vi.fn(),
adminUpdateItem: vi.fn(),
adminDeleteItem: vi.fn(),
}));
vi.mock('../../components/LexicalEditor', () => ({
LexicalEditor: ({
initialHtml,
onChange,
}: {
initialHtml: string;
onChange: (html: string) => void;
placeholder?: string;
}) => (
<div data-testid="lexical-stub">
<textarea
data-testid="editor-body"
defaultValue={initialHtml}
aria-label="Item content"
onChange={(event) => onChange(event.target.value)}
/>
</div>
),
}));
vi.mock('../../api/client', async () => {
const actual = await vi.importActual<typeof import('../../api/client')>(
'../../api/client',
);
return {
...actual,
me: vi.fn(),
login: vi.fn(),
register: vi.fn(),
logout: vi.fn(),
TOKEN_KEY: 'AUTH_TOKEN',
};
});
const ITEM: AdminItem = {
id: 5,
title: 'Original headline',
url: 'https://example.com/original',
points: 11,
username: 'alice',
content: '<p>Original body</p>',
created_at: '2024-05-01T12:00:00Z',
};
function DashboardStub() {
const location = useLocation();
const notice = (location.state as { notice?: string } | null)?.notice ?? '';
return (
<div data-testid="dashboard-stub">
{notice && <p data-testid="dashboard-notice">{notice}</p>}
</div>
);
}
function renderAt(path: string) {
return render(
<MemoryRouter
initialEntries={[path]}
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
>
<AuthProvider>
<Routes>
<Route path="/admin" element={<DashboardStub />} />
<Route path="/admin/items/new" element={<EditPage />} />
<Route path="/admin/items/:id/edit" element={<EditPage />} />
</Routes>
</AuthProvider>
</MemoryRouter>,
);
}
describe('EditItemPage (create)', () => {
beforeEach(() => {
localStorage.clear();
vi.clearAllMocks();
(clientMe as Mock).mockResolvedValue({ username: 'root', is_admin: true });
localStorage.setItem(TOKEN_KEY, 'token');
vi.mocked(adminCreateItem).mockResolvedValue({ ...ITEM, id: 99 });
vi.mocked(adminUpdateItem).mockResolvedValue(ITEM);
});
it('pre-fills the author with the signed-in admin', async () => {
renderAt('/admin/items/new');
await screen.findByTestId('lexical-stub');
expect(screen.getByLabelText('Author')).toHaveValue('root');
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('New item');
});
it('blocks submission with an empty title and does not call the API', async () => {
renderAt('/admin/items/new');
await screen.findByTestId('lexical-stub');
screen.getByRole('button', { name: /create item/i }).click();
// The field error and the form-level error are both alerts.
const alerts = await screen.findAllByRole('alert');
expect(
alerts.some((el) => /title is required/i.test(el.textContent ?? '')),
).toBe(true);
expect(vi.mocked(adminCreateItem)).not.toHaveBeenCalled();
expect(screen.queryByTestId('dashboard-stub')).not.toBeInTheDocument();
});
it('rejects an invalid URL client-side', async () => {
renderAt('/admin/items/new');
await screen.findByTestId('lexical-stub');
fireEvent.change(screen.getByLabelText(/^Title/), { target: { value: 'Has url' } });
fireEvent.change(screen.getByLabelText(/^URL/), {
target: { value: 'not a url' },
});
screen.getByRole('button', { name: /create item/i }).click();
const alerts = await screen.findAllByRole('alert');
expect(
alerts.some((el) => /http:\/\/ or https:\/\//i.test(el.textContent ?? '')),
).toBe(true);
expect(vi.mocked(adminCreateItem)).not.toHaveBeenCalled();
});
it('creates the item with trimmed values and navigates back with a notice', async () => {
renderAt('/admin/items/new');
await screen.findByTestId('lexical-stub');
fireEvent.change(screen.getByLabelText(/^Title/), {
target: { value: ' Fresh story ' },
});
fireEvent.change(screen.getByLabelText(/^URL/), {
target: { value: ' https://example.com/fresh ' },
});
fireEvent.change(screen.getByLabelText('Points'), { target: { value: '7' } });
fireEvent.change(screen.getByTestId('editor-body'), {
target: { value: '<p>Body <strong>here</strong></p>' },
});
screen.getByRole('button', { name: /create item/i }).click();
await waitFor(() =>
expect(vi.mocked(adminCreateItem)).toHaveBeenCalledWith({
title: 'Fresh story',
url: 'https://example.com/fresh',
points: 7,
username: 'root',
content: '<p>Body <strong>here</strong></p>',
}),
);
expect(await screen.findByTestId('dashboard-stub')).toBeInTheDocument();
expect(screen.getByTestId('dashboard-notice')).toHaveTextContent(
'“Fresh story” was saved.',
);
});
it('disables the create button while the request is in flight', async () => {
let resolveCreate!: (value: AdminItem) => void;
vi.mocked(adminCreateItem).mockReturnValueOnce(
new Promise<AdminItem>((resolve) => {
resolveCreate = resolve;
}),
);
renderAt('/admin/items/new');
await screen.findByTestId('lexical-stub');
fireEvent.change(screen.getByLabelText(/^Title/), {
target: { value: 'Pending' },
});
screen.getByRole('button', { name: /create item/i }).click();
const button = screen.getByRole('button', { name: /create item/i });
await waitFor(() => expect(button).toBeDisabled());
resolveCreate({ ...ITEM, id: 99, title: 'Pending' });
expect(await screen.findByTestId('dashboard-stub')).toBeInTheDocument();
});
it('shows the backend error when the create request fails', async () => {
vi.mocked(adminCreateItem).mockRejectedValue(
new ApiError(422, 'Validation failed', 'validation_error'),
);
renderAt('/admin/items/new');
await screen.findByTestId('lexical-stub');
fireEvent.change(screen.getByLabelText(/^Title/), { target: { value: 'x' } });
screen.getByRole('button', { name: /create item/i }).click();
expect(await screen.findByRole('alert')).toHaveTextContent('Validation failed');
});
});
describe('EditItemPage (edit)', () => {
beforeEach(() => {
localStorage.clear();
vi.clearAllMocks();
(clientMe as Mock).mockResolvedValue({ username: 'root', is_admin: true });
localStorage.setItem(TOKEN_KEY, 'token');
vi.mocked(adminGetItem).mockResolvedValue(ITEM);
vi.mocked(adminUpdateItem).mockResolvedValue(ITEM);
});
it('loads and pre-fills the item, then updates it on save', async () => {
renderAt('/admin/items/5/edit');
// Loading state first.
expect(screen.getByRole('status')).toHaveTextContent(/loading item/i);
await screen.findByTestId('lexical-stub');
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent(
'Edit item #5',
);
expect(screen.getByLabelText(/^Title/)).toHaveValue('Original headline');
expect(screen.getByLabelText(/^URL/)).toHaveValue('https://example.com/original');
expect(screen.getByLabelText('Points')).toHaveValue(11);
expect(screen.getByLabelText('Author')).toHaveValue('alice');
expect(screen.getByTestId('editor-body')).toHaveValue('<p>Original body</p>');
fireEvent.change(screen.getByLabelText(/^Title/), {
target: { value: 'Retitled' },
});
screen.getByRole('button', { name: /save changes/i }).click();
await waitFor(() =>
expect(vi.mocked(adminUpdateItem)).toHaveBeenCalledWith(5, {
title: 'Retitled',
url: 'https://example.com/original',
points: 11,
username: 'alice',
content: '<p>Original body</p>',
}),
);
expect(await screen.findByTestId('dashboard-stub')).toBeInTheDocument();
});
it('shows the not-found view when the item cannot be loaded', async () => {
vi.mocked(adminGetItem).mockRejectedValue(
Object.assign(new Error('Item not found'), { status: 404 }),
);
renderAt('/admin/items/999/edit');
expect(await screen.findByRole('heading', { level: 1 })).toHaveTextContent(
/item not found/i,
);
expect(screen.getByRole('link', { name: /back to items/i })).toHaveAttribute(
'href',
'/admin',
);
});
});