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
290 lines
9.8 KiB
TypeScript
290 lines
9.8 KiB
TypeScript
/**
|
|
* 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',
|
|
);
|
|
});
|
|
});
|