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.
This commit is contained in:
1 parent
b186d0f797
commit
b440809548
38 files changed
+5415
-50
No files matched your search
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* Unit tests for the admin API client (URL/parameter building, methods,
|
||||
* response parsing, error propagation).
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
adminCreateItem,
|
||||
adminDeleteItem,
|
||||
adminGetItem,
|
||||
adminListItems,
|
||||
adminUpdateItem,
|
||||
} from '../../api/admin';
|
||||
import { ApiError, TOKEN_KEY } from '../../api/client';
|
||||
import type { AdminItemsPage } from '../../types/admin';
|
||||
|
||||
const SAMPLE_PAGE: AdminItemsPage = {
|
||||
items: [
|
||||
{
|
||||
id: 1,
|
||||
title: 'First story',
|
||||
url: 'https://example.com/first',
|
||||
points: 3,
|
||||
username: 'alice',
|
||||
content: '<p>Hello</p>',
|
||||
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<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
fetchMock = vi.fn();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
});
|
||||
|
||||
it('listItems builds the query string from all parameters', async () => {
|
||||
localStorage.setItem(TOKEN_KEY, 'admin-token');
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE));
|
||||
|
||||
const res = await adminListItems({
|
||||
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/items?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<string, string>).Authorization).toBe(
|
||||
'Bearer admin-token',
|
||||
);
|
||||
});
|
||||
|
||||
it('listItems omits the search parameter when empty', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE));
|
||||
|
||||
await adminListItems({
|
||||
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/items?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]));
|
||||
|
||||
await adminGetItem(7);
|
||||
|
||||
const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/admin/items/7');
|
||||
});
|
||||
|
||||
it('createItem POSTs the payload', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(201, SAMPLE_PAGE.items[0]));
|
||||
|
||||
await adminCreateItem({
|
||||
title: 'New story',
|
||||
url: '',
|
||||
points: 0,
|
||||
username: 'root',
|
||||
content: '<p>Body</p>',
|
||||
});
|
||||
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/admin/items');
|
||||
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>',
|
||||
});
|
||||
});
|
||||
|
||||
it('updateItem PUTs the payload to the item route', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE.items[0]));
|
||||
|
||||
await adminUpdateItem(7, {
|
||||
title: 'Updated',
|
||||
url: 'https://example.com/new',
|
||||
points: 9,
|
||||
username: 'root',
|
||||
content: '',
|
||||
});
|
||||
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/admin/items/7');
|
||||
expect(init.method).toBe('PUT');
|
||||
});
|
||||
|
||||
it('deleteItem 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();
|
||||
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/admin/items/7');
|
||||
expect(init.method).toBe('DELETE');
|
||||
});
|
||||
|
||||
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({
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,224 @@
|
||||
/**
|
||||
* 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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* Tests for the DeleteConfirmation modal (M6): warning layout, explicit
|
||||
* "Yes, delete" confirmation, cancel/Escape/overlay dismissal and the
|
||||
* busy state while the request is in flight.
|
||||
*/
|
||||
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';
|
||||
|
||||
const ITEM: AdminItem = {
|
||||
id: 42,
|
||||
title: 'Breaking: the sky is falling',
|
||||
url: 'https://example.com/sky',
|
||||
points: 12,
|
||||
username: 'alice',
|
||||
content: '<p>…</p>',
|
||||
created_at: '2024-05-01T12:00:00Z',
|
||||
};
|
||||
|
||||
function renderModal(props: Partial<Parameters<typeof DeleteConfirmation>[0]> = {}) {
|
||||
const onConfirm = vi.fn();
|
||||
const onCancel = vi.fn();
|
||||
const utils = render(
|
||||
<DeleteConfirmation
|
||||
item={ITEM}
|
||||
onConfirm={onConfirm}
|
||||
onCancel={onCancel}
|
||||
{...props}
|
||||
/>,
|
||||
);
|
||||
return { onConfirm, onCancel, ...utils };
|
||||
}
|
||||
|
||||
describe('DeleteConfirmation', () => {
|
||||
it('shows the warning layout with the item title', () => {
|
||||
renderModal();
|
||||
|
||||
const dialog = screen.getByRole('dialog');
|
||||
expect(
|
||||
screen.getByRole('heading', { name: /are you sure you want to delete/i }),
|
||||
).toBeInTheDocument();
|
||||
expect(dialog).toHaveTextContent('Breaking: the sky is falling');
|
||||
expect(dialog).toHaveTextContent(/cannot be undone/i);
|
||||
expect(
|
||||
screen.getByRole('button', { name: /yes, delete/i }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /cancel/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onConfirm when "Yes, delete" is clicked', () => {
|
||||
const { onConfirm } = renderModal();
|
||||
|
||||
fireEvent.click(screen.getByTestId('confirm-delete'));
|
||||
|
||||
expect(onConfirm).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('calls onCancel when Cancel is clicked', () => {
|
||||
const { onCancel } = renderModal();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /cancel/i }));
|
||||
|
||||
expect(onCancel).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('closes on overlay click but not on dialog click', () => {
|
||||
const { onCancel } = renderModal();
|
||||
const dialog = screen.getByRole('dialog');
|
||||
const overlay = dialog.parentElement as HTMLElement;
|
||||
|
||||
fireEvent.click(overlay);
|
||||
expect(onCancel).toHaveBeenCalledTimes(1);
|
||||
|
||||
fireEvent.click(dialog);
|
||||
expect(onCancel).toHaveBeenCalledTimes(1); // unchanged — stopPropagation
|
||||
});
|
||||
|
||||
it('closes on the Escape key', () => {
|
||||
const { onCancel } = renderModal();
|
||||
|
||||
act(() => {
|
||||
fireEvent.keyDown(document, { key: 'Escape' });
|
||||
});
|
||||
|
||||
expect(onCancel).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('disables both actions and ignores Escape while busy', () => {
|
||||
const { onCancel } = renderModal({ busy: true });
|
||||
|
||||
const confirm = screen.getByRole('button', { name: /deleting…/i });
|
||||
const cancel = screen.getByRole('button', { name: /cancel/i });
|
||||
expect(confirm).toBeDisabled();
|
||||
expect(cancel).toBeDisabled();
|
||||
expect(confirm).toHaveTextContent(/deleting…/i);
|
||||
|
||||
act(() => {
|
||||
fireEvent.keyDown(document, { key: 'Escape' });
|
||||
});
|
||||
fireEvent.click(cancel);
|
||||
|
||||
expect(onCancel).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('renders an error message when provided', () => {
|
||||
renderModal({ error: 'Deleting the item failed.' });
|
||||
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Deleting the item failed.');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,253 @@
|
||||
/**
|
||||
* 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('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',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* Tests for the RequireAdmin route guard (M6): signed-out users are
|
||||
* redirected to /login, authenticated non-admins see the 403 page, and
|
||||
* admins get the protected content.
|
||||
*/
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import { TOKEN_KEY, me as clientMe } from '../../api/client';
|
||||
import { AuthProvider, RequireAdmin } from '../../auth';
|
||||
|
||||
vi.mock('../../api/client', () => ({
|
||||
TOKEN_KEY: 'AUTH_TOKEN',
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
me: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
const routes = (
|
||||
<Routes>
|
||||
<Route path="/login" element={<div>Login page</div>} />
|
||||
<Route
|
||||
path="/admin"
|
||||
element={
|
||||
<RequireAdmin>
|
||||
<div data-testid="admin-content">Admin dashboard</div>
|
||||
</RequireAdmin>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
);
|
||||
|
||||
function renderAt(path: string) {
|
||||
return render(
|
||||
<MemoryRouter
|
||||
initialEntries={[path]}
|
||||
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||||
>
|
||||
<AuthProvider>{routes}</AuthProvider>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('RequireAdmin', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('redirects signed-out users to /login', async () => {
|
||||
renderAt('/admin');
|
||||
expect(await screen.findByText('Login page')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the 403 page for an authenticated non-admin', async () => {
|
||||
(clientMe as Mock).mockResolvedValue({ username: 'alice', is_admin: false });
|
||||
localStorage.setItem(TOKEN_KEY, 'token');
|
||||
|
||||
renderAt('/admin');
|
||||
|
||||
expect(await screen.findByTestId('forbidden-page')).toBeInTheDocument();
|
||||
expect(screen.getByRole('heading', { level: 1, name: '403' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('alert')).toHaveTextContent(/admin area/i);
|
||||
expect(screen.queryByTestId('admin-content')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('treats a missing is_admin flag as non-admin (defensive)', async () => {
|
||||
(clientMe as Mock).mockResolvedValue({ username: 'alice' });
|
||||
localStorage.setItem(TOKEN_KEY, 'token');
|
||||
|
||||
renderAt('/admin');
|
||||
|
||||
expect(await screen.findByTestId('forbidden-page')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders the protected content for an admin', async () => {
|
||||
(clientMe as Mock).mockResolvedValue({ username: 'root', is_admin: true });
|
||||
localStorage.setItem(TOKEN_KEY, 'token');
|
||||
|
||||
renderAt('/admin');
|
||||
|
||||
expect(await screen.findByTestId('admin-content')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('forbidden-page')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user