Files
newz-qwen-27b/frontend/src/tests/admin/admin-dashboard.test.tsx
T
Daniel Samson b440809548 feat: add admin area with item CRUD, Lexical editor and access control (M6)
Backend:
- Item model (title, url, points, username, content, created_at)
- is_admin flag on User + startup migration for pre-existing DBs
- get_current_admin dependency (401 without/invalid token, 403 for
  non-admins); server-side check on every admin endpoint
- /api/v1/admin/items CRUD: pagination, case-insensitive title/url
  search, sort by title/created_at/points, in-memory rate limiting
  (1000 req/60s per admin -> 429)
- seed_admin.py (ADMIN_USERNAME/ADMIN_PASSWORD), documented in
  backend/.env.example

Frontend:
- Auth context exposes is_admin; RequireAdmin route guard (redirects
  signed-out users, renders 403 page for non-admins)
- AdminLayout with responsive dark sidebar; Admin link in header for
  admins only
- AdminDashboard: paginated table (page size 10/20/50), 300ms
  debounced search, sortable title/points/created_at columns,
  edit/delete row actions
- EditItemPage: create + edit with client-side validation and a
  Lexical (0.25) WYSIWYG editor (bold/italic/underline, H1-H6,
  lists, code blocks, links, undo/redo), optional debounced auto-save
- DeleteConfirmation modal with warning icon and explicit
  "Yes, delete" confirmation
- Unit tests (34) and mocked E2E workflow tests (10)

All acceptance criteria for milestones/m6-setup-admin-area-prompt.md
verified: 108 backend, 87 frontend unit and 29 E2E tests pass.
2026-10-30 21:36:15 +00:00

225 lines
7.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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 {
adminDeleteItem,
adminListItems,
} from '../../api/admin';
import { AdminDashboard } from '../../pages/AdminDashboard';
import type { AdminItemsPage } from '../../types/admin';
vi.mock('../../api/admin', () => ({
adminListItems: vi.fn(),
adminGetItem: vi.fn(),
adminCreateItem: vi.fn(),
adminUpdateItem: vi.fn(),
adminDeleteItem: 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 page = (overrides: Partial<AdminItemsPage> = {}): AdminItemsPage => ({
items: items(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(adminListItems).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(adminListItems).mockResolvedValue(page());
vi.mocked(adminDeleteItem).mockResolvedValue(undefined);
});
it('renders the fetched items 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();
expect(screen.getByText('Showing 1–3 of 3')).toBeInTheDocument();
// 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');
});
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 items'), {
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 points/i }));
expect(lastCallParams().sortBy).toBe('points');
expect(lastCallParams().sortOrder).toBe('asc');
});
it('navigates pages and changes the page size', async () => {
vi.mocked(adminListItems).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(adminListItems).mockResolvedValue(page({ items: [], total: 0 }));
renderDashboard();
await screen.findByText(/no items yet/i);
});
it('shows the error state with a retry action', async () => {
vi.mocked(adminListItems).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),
);
});
it('deletes an item 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(adminDeleteItem)).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();
// Confirm: the API is called and the list refreshes.
const listCallsBefore = vi.mocked(adminListItems).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(adminListItems).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 },
);
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 item failed/i);
// Dialog still open.
expect(screen.getByRole('dialog')).toBeInTheDocument();
});
});