Files
ReadMeABook/tests/app/search.page.test.tsx
kikootwo d25a6ebf79 Add custom search terms & retry download (admin)
Add support for per-request custom search terms and an admin retry-download flow.

- DB/schema: add custom_search_terms column via Prisma migration and schema update.
- Admin UI: new AdjustSearchTermsModal component and UI badges to show custom search status; RequestActionsDropdown and RecentRequestsTable updated to surface adjust/retry actions.
- API: new PATCH /api/admin/requests/[id]/search-terms to set/clear custom terms (optionally trigger a new search) and new POST /api/admin/requests/[id]/retry-download to resume monitoring or re-add downloads using DownloadHistory metadata.
- Behavior: interactive search now prefers customSearchTerms when present; manual import exposes cleanupSource option to organize job; admin requests listing returns downloadAttempts and customSearchTerms.
- UX: add SectionToolbar, LoadMoreBar and HideAvailableToggle components and wire hide-available preference across home, search, author and series pages; authors/series endpoints/page handlers gain pagination metadata.
- Misc: add connection-errors util and update related processors/services and tests to cover the new flows.

These changes enable admins to override search terms per request, trigger searches from the admin UI, and retry failed downloads more robustly.
2026-03-02 17:05:21 -05:00

146 lines
3.9 KiB
TypeScript

/**
* Component: Search Page Tests
* Documentation: documentation/frontend/components.md
*/
// @vitest-environment jsdom
import React from 'react';
import { act, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { resetMockAuthState } from '../helpers/mock-auth';
import { resetMockRouter } from '../helpers/mock-next-navigation';
const loadMoreMock = vi.hoisted(() => vi.fn());
const useSearchMock = vi.hoisted(() => vi.fn());
const usePreferencesMock = vi.hoisted(() => ({
cardSize: 5,
setCardSize: vi.fn(),
squareCovers: false,
setSquareCovers: vi.fn(),
hideAvailable: false,
setHideAvailable: vi.fn(),
}));
vi.mock('@/lib/hooks/useAudiobooks', () => ({
useSearch: useSearchMock,
Audiobook: {},
}));
vi.mock('@/contexts/PreferencesContext', () => ({
usePreferences: () => usePreferencesMock,
}));
vi.mock('@/components/auth/ProtectedRoute', () => ({
ProtectedRoute: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));
vi.mock('@/components/layout/Header', () => ({
Header: () => <div data-testid="header" />,
}));
vi.mock('@/components/audiobooks/AudiobookGrid', () => ({
AudiobookGrid: ({
audiobooks,
emptyMessage,
cardSize,
}: {
audiobooks: any[];
emptyMessage: string;
cardSize?: number;
}) => (
<div data-testid="grid" data-count={audiobooks.length} data-size={cardSize}>
<span>{emptyMessage}</span>
</div>
),
}));
vi.mock('@/components/ui/SectionToolbar', () => ({
SectionToolbar: () => <div data-testid="section-toolbar" />,
}));
vi.mock('@/components/ui/LoadMoreBar', () => ({
LoadMoreBar: ({
hasMore,
isLoading,
onLoadMore,
}: {
loadedCount: number;
totalCount?: number;
hasMore: boolean;
isLoading: boolean;
onLoadMore: () => void;
itemLabel?: string;
}) =>
hasMore ? (
<button onClick={onLoadMore} disabled={isLoading}>
Load more
</button>
) : (
<div data-testid="all-loaded">All loaded</div>
),
}));
describe('SearchPage', () => {
beforeEach(() => {
resetMockAuthState();
resetMockRouter();
useSearchMock.mockReset();
loadMoreMock.mockReset();
usePreferencesMock.cardSize = 5;
usePreferencesMock.setCardSize.mockReset();
vi.useFakeTimers();
vi.resetModules();
});
afterEach(() => {
vi.useRealTimers();
});
it('shows the empty state before a search query is entered', async () => {
useSearchMock.mockReturnValue({
results: [],
totalResults: 0,
hasMore: false,
isLoading: false,
isLoadingMore: false,
loadMore: loadMoreMock,
});
const { default: SearchPage } = await import('@/app/search/page');
render(<SearchPage />);
expect(screen.getByText('Start typing to search for audiobooks')).toBeInTheDocument();
expect(useSearchMock).toHaveBeenCalledWith('');
});
it('debounces search input and loads more results', async () => {
useSearchMock.mockReturnValue({
results: [{ asin: 'a1', title: 'Book One', author: 'Author' }],
totalResults: 2,
hasMore: true,
isLoading: false,
isLoadingMore: false,
loadMore: loadMoreMock,
});
const { default: SearchPage } = await import('@/app/search/page');
render(<SearchPage />);
const input = screen.getByPlaceholderText('Search by title, author, or narrator...');
fireEvent.change(input, { target: { value: 'Dune' } });
await act(async () => {
vi.advanceTimersByTime(500);
});
expect(screen.getByText('Search Results')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Load more' })).toBeInTheDocument();
expect(screen.getByTestId('grid')).toHaveAttribute('data-count', '1');
fireEvent.click(screen.getByRole('button', { name: 'Load more' }));
expect(loadMoreMock).toHaveBeenCalled();
});
});