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
245 lines
8.4 KiB
TypeScript
245 lines
8.4 KiB
TypeScript
/**
|
||
* Tests for the AdminDashboard list view (M6): rendering, debounced
|
||
* search, sorting, pagination and the delete confirmation flow.
|
||
*/
|
||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||
import { MemoryRouter } from 'react-router-dom';
|
||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||
import {
|
||
adminDeleteArticle,
|
||
adminListArticles,
|
||
} from '../../api/admin';
|
||
import { AdminDashboard } from '../../pages/AdminDashboard';
|
||
import type { AdminArticlesPage } 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(),
|
||
}));
|
||
|
||
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 = (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,
|
||
total_pages: 1,
|
||
...overrides,
|
||
});
|
||
|
||
function lastCallParams(): {
|
||
page: number;
|
||
pageSize: number;
|
||
search: string;
|
||
sortBy: string;
|
||
sortOrder: string;
|
||
} {
|
||
const calls = vi.mocked(adminListArticles).mock.calls;
|
||
const last = calls[calls.length - 1][0];
|
||
return {
|
||
page: last.page,
|
||
pageSize: last.pageSize,
|
||
search: last.search,
|
||
sortBy: last.sortBy,
|
||
sortOrder: last.sortOrder,
|
||
};
|
||
}
|
||
|
||
function renderDashboard() {
|
||
return render(
|
||
<MemoryRouter
|
||
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||
>
|
||
<AdminDashboard />
|
||
</MemoryRouter>,
|
||
);
|
||
}
|
||
|
||
describe('AdminDashboard', () => {
|
||
beforeEach(() => {
|
||
vi.clearAllMocks();
|
||
vi.mocked(adminListArticles).mockResolvedValue(page());
|
||
vi.mocked(adminDeleteArticle).mockResolvedValue(undefined);
|
||
});
|
||
|
||
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();
|
||
// 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/articles/1/edit');
|
||
});
|
||
|
||
it('requests the initial page with the default parameters', async () => {
|
||
renderDashboard();
|
||
await screen.findByText('Story 1');
|
||
expect(lastCallParams()).toEqual({
|
||
page: 1,
|
||
pageSize: 20,
|
||
search: '',
|
||
sortBy: 'created_at',
|
||
sortOrder: 'desc',
|
||
});
|
||
});
|
||
|
||
it('debounces the search and filters by it', async () => {
|
||
renderDashboard();
|
||
await screen.findByText('Story 1');
|
||
|
||
fireEvent.change(screen.getByLabelText('Search articles'), {
|
||
target: { value: 'breaking' },
|
||
});
|
||
|
||
// Immediately after typing: still the original request (debounce).
|
||
expect(lastCallParams().search).toBe('');
|
||
|
||
// After the 300ms debounce the API is called with the search term.
|
||
await waitFor(() => expect(lastCallParams().search).toBe('breaking'), {
|
||
timeout: 1500,
|
||
});
|
||
// Searching resets to page 1.
|
||
expect(lastCallParams().page).toBe(1);
|
||
});
|
||
|
||
it('toggles sort direction when clicking the same column twice', async () => {
|
||
renderDashboard();
|
||
await screen.findByText('Story 1');
|
||
|
||
fireEvent.click(screen.getByRole('button', { name: /sort by title/i }));
|
||
expect(lastCallParams().sortBy).toBe('title');
|
||
expect(lastCallParams().sortOrder).toBe('asc');
|
||
|
||
fireEvent.click(screen.getByRole('button', { name: /sort by title/i }));
|
||
expect(lastCallParams().sortBy).toBe('title');
|
||
expect(lastCallParams().sortOrder).toBe('desc');
|
||
|
||
// Switching columns starts on ascending again.
|
||
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(adminListArticles).mockResolvedValue(
|
||
page({ total: 45, page: 2, total_pages: 3 }),
|
||
);
|
||
renderDashboard();
|
||
await screen.findByText('Story 1');
|
||
|
||
fireEvent.click(screen.getByRole('button', { name: /next/i }));
|
||
await waitFor(() => expect(lastCallParams().page).toBe(2));
|
||
|
||
fireEvent.click(screen.getByRole('button', { name: /previous/i }));
|
||
await waitFor(() => expect(lastCallParams().page).toBe(1));
|
||
|
||
fireEvent.change(screen.getByLabelText('Rows per page'), {
|
||
target: { value: '50' },
|
||
});
|
||
await waitFor(() => expect(lastCallParams().pageSize).toBe(50));
|
||
expect(lastCallParams().page).toBe(1);
|
||
});
|
||
|
||
it('shows an empty state when nothing matches the search', async () => {
|
||
vi.mocked(adminListArticles).mockResolvedValue(page({ articles: [], total: 0 }));
|
||
renderDashboard();
|
||
await screen.findByText(/no articles yet/i);
|
||
});
|
||
|
||
it('shows the error state with a retry action', async () => {
|
||
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(adminListArticles).mock.calls.length).toBeGreaterThanOrEqual(2),
|
||
);
|
||
});
|
||
|
||
it('deletes an article only after explicit confirmation', async () => {
|
||
renderDashboard();
|
||
await screen.findByText('Story 1');
|
||
|
||
// Open the dialog.
|
||
fireEvent.click(screen.getAllByRole('button', { name: /delete/i })[0]);
|
||
const dialog = await screen.findByRole('dialog');
|
||
expect(dialog).toHaveTextContent('Story 1');
|
||
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(adminDeleteArticle)).not.toHaveBeenCalled();
|
||
|
||
// Confirm: the API is called and the list refreshes.
|
||
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(adminDeleteArticle)).toHaveBeenCalledWith(1),
|
||
);
|
||
expect(
|
||
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(adminDeleteArticle).mockRejectedValue(
|
||
new Error('Deleting the article failed.') as Error & { status?: number },
|
||
);
|
||
renderDashboard();
|
||
await screen.findByText('Story 1');
|
||
|
||
fireEvent.click(screen.getAllByRole('button', { name: /delete/i })[0]);
|
||
await screen.findByRole('dialog');
|
||
fireEvent.click(screen.getByRole('button', { name: /yes, delete/i }));
|
||
|
||
const alert = await screen.findByRole('alert');
|
||
expect(alert).toHaveTextContent(/deleting the article failed/i);
|
||
// Dialog still open.
|
||
expect(screen.getByRole('dialog')).toBeInTheDocument();
|
||
});
|
||
});
|