mirror of
https://github.com/kikootwo/ReadMeABook.git
synced 2026-06-02 20:30:10 +00:00
Add series fields to audiobooks and update related logic
Introduces 'series' and 'seriesPart' fields to the Audiobook model and database schema. Updates API routes, file organization, and path template utilities to support series metadata. Enhances chapter merging logic, improves notification backend testing, and expands test coverage for admin and API routes.
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Component: Flag Config Row Tests
|
||||
* Documentation: documentation/phase3/ranking-algorithm.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { FlagConfigRow } from '@/components/admin/FlagConfigRow';
|
||||
import type { IndexerFlagConfig } from '@/lib/utils/ranking-algorithm';
|
||||
|
||||
describe('FlagConfigRow', () => {
|
||||
it('updates name and modifier values and allows removal', () => {
|
||||
const onChange = vi.fn();
|
||||
const onRemove = vi.fn();
|
||||
const config: IndexerFlagConfig = { name: 'Freeleech', modifier: 20 };
|
||||
|
||||
render(<FlagConfigRow config={config} onChange={onChange} onRemove={onRemove} />);
|
||||
|
||||
fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Internal' } });
|
||||
fireEvent.change(screen.getByRole('slider'), { target: { value: '-15' } });
|
||||
fireEvent.click(screen.getByTitle('Remove flag rule'));
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({ name: 'Internal', modifier: 20 });
|
||||
expect(onChange).toHaveBeenCalledWith({ name: 'Freeleech', modifier: -15 });
|
||||
expect(onRemove).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('shows disqualification warning for large negative modifiers', () => {
|
||||
render(
|
||||
<FlagConfigRow
|
||||
config={{ name: 'Bad', modifier: -60 }}
|
||||
onChange={vi.fn()}
|
||||
onRemove={vi.fn()}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText(/Would disqualify/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Component: Available Indexer Row Tests
|
||||
* Documentation: documentation/frontend/components.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { AvailableIndexerRow } from '@/components/admin/indexers/AvailableIndexerRow';
|
||||
|
||||
describe('AvailableIndexerRow', () => {
|
||||
const indexer = {
|
||||
id: 1,
|
||||
name: 'Test Indexer',
|
||||
protocol: 'torrent',
|
||||
supportsRss: true,
|
||||
};
|
||||
|
||||
it('renders an add button when the indexer is not added', () => {
|
||||
const onAdd = vi.fn();
|
||||
|
||||
render(<AvailableIndexerRow indexer={indexer} isAdded={false} onAdd={onAdd} />);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add' }));
|
||||
|
||||
expect(onAdd).toHaveBeenCalledTimes(1);
|
||||
expect(screen.getByText('Test Indexer')).toBeInTheDocument();
|
||||
expect(screen.getByText('torrent')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders the added state when already configured', () => {
|
||||
render(<AvailableIndexerRow indexer={indexer} isAdded onAdd={vi.fn()} />);
|
||||
|
||||
expect(screen.getByText('Added')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Add' })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Component: Category Tree View Tests
|
||||
* Documentation: documentation/frontend/components.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen, within } from '@testing-library/react';
|
||||
import { CategoryTreeView } from '@/components/admin/indexers/CategoryTreeView';
|
||||
import { getChildIds } from '@/lib/utils/torrent-categories';
|
||||
|
||||
describe('CategoryTreeView', () => {
|
||||
it('selects parent and children when the parent is toggled', () => {
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(<CategoryTreeView selectedCategories={[]} onChange={onChange} />);
|
||||
|
||||
const audioLabel = screen.getByText('Audio');
|
||||
const audioRow = audioLabel.closest('div')?.parentElement;
|
||||
if (!audioRow) {
|
||||
throw new Error('Audio parent row not found');
|
||||
}
|
||||
|
||||
fireEvent.click(within(audioRow).getByRole('switch'));
|
||||
|
||||
const audioChildren = getChildIds(3000);
|
||||
expect(onChange).toHaveBeenCalledWith(
|
||||
expect.arrayContaining([3000, ...audioChildren])
|
||||
);
|
||||
});
|
||||
|
||||
it('toggles a child category on and off', () => {
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(<CategoryTreeView selectedCategories={[]} onChange={onChange} />);
|
||||
|
||||
const audiobookLabel = screen.getByText('Audiobook');
|
||||
const audiobookRow = audiobookLabel.closest('div')?.parentElement;
|
||||
if (!audiobookRow) {
|
||||
throw new Error('Audiobook row not found');
|
||||
}
|
||||
|
||||
fireEvent.click(within(audiobookRow).getByRole('switch'));
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith(expect.arrayContaining([3030]));
|
||||
});
|
||||
|
||||
it('disables child toggles when all children are selected', () => {
|
||||
const audioChildren = getChildIds(3000);
|
||||
|
||||
render(
|
||||
<CategoryTreeView
|
||||
selectedCategories={[3000, ...audioChildren]}
|
||||
onChange={vi.fn()}
|
||||
/>
|
||||
);
|
||||
|
||||
const audiobookLabel = screen.getByText('Audiobook');
|
||||
const audiobookRow = audiobookLabel.closest('div')?.parentElement;
|
||||
if (!audiobookRow) {
|
||||
throw new Error('Audiobook row not found');
|
||||
}
|
||||
|
||||
expect(within(audiobookRow).getByRole('switch')).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Component: Delete Confirm Modal Tests
|
||||
* Documentation: documentation/frontend/components.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { DeleteConfirmModal } from '@/components/admin/indexers/DeleteConfirmModal';
|
||||
|
||||
describe('DeleteConfirmModal', () => {
|
||||
it('confirms removal and closes the modal', () => {
|
||||
const onClose = vi.fn();
|
||||
const onConfirm = vi.fn();
|
||||
|
||||
render(
|
||||
<DeleteConfirmModal
|
||||
isOpen
|
||||
onClose={onClose}
|
||||
onConfirm={onConfirm}
|
||||
indexerName="TrackerOne"
|
||||
/>
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Remove Indexer' }));
|
||||
|
||||
expect(onConfirm).toHaveBeenCalledTimes(1);
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('closes without confirming when canceled', () => {
|
||||
const onClose = vi.fn();
|
||||
|
||||
render(
|
||||
<DeleteConfirmModal
|
||||
isOpen
|
||||
onClose={onClose}
|
||||
onConfirm={vi.fn()}
|
||||
indexerName="TrackerTwo"
|
||||
/>
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Component: Indexer Card Tests
|
||||
* Documentation: documentation/frontend/components.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { IndexerCard } from '@/components/admin/indexers/IndexerCard';
|
||||
|
||||
describe('IndexerCard', () => {
|
||||
it('renders indexer info and triggers edit/delete actions', () => {
|
||||
const onEdit = vi.fn();
|
||||
const onDelete = vi.fn();
|
||||
|
||||
render(
|
||||
<IndexerCard
|
||||
indexer={{ id: 2, name: 'IndexerTwo', protocol: 'usenet' }}
|
||||
onEdit={onEdit}
|
||||
onDelete={onDelete}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('IndexerTwo')).toBeInTheDocument();
|
||||
expect(screen.getByText('usenet')).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByTitle('Edit indexer'));
|
||||
fireEvent.click(screen.getByTitle('Delete indexer'));
|
||||
|
||||
expect(onEdit).toHaveBeenCalledTimes(1);
|
||||
expect(onDelete).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* Component: Indexer Config Modal Tests
|
||||
* Documentation: documentation/frontend/components.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen, within } from '@testing-library/react';
|
||||
import { IndexerConfigModal } from '@/components/admin/indexers/IndexerConfigModal';
|
||||
|
||||
describe('IndexerConfigModal', () => {
|
||||
it('clamps numeric inputs and saves configuration', () => {
|
||||
const onSave = vi.fn();
|
||||
const onClose = vi.fn();
|
||||
|
||||
render(
|
||||
<IndexerConfigModal
|
||||
isOpen
|
||||
onClose={onClose}
|
||||
mode="add"
|
||||
indexer={{ id: 1, name: 'Prowlarr', protocol: 'torrent', supportsRss: true }}
|
||||
onSave={onSave}
|
||||
/>
|
||||
);
|
||||
|
||||
const [priorityInput, seedingInput] = screen.getAllByRole('spinbutton');
|
||||
|
||||
fireEvent.change(priorityInput, { target: { value: '99' } });
|
||||
expect(priorityInput).toHaveValue(25);
|
||||
|
||||
fireEvent.change(seedingInput, { target: { value: '-5' } });
|
||||
expect(seedingInput).toHaveValue(0);
|
||||
|
||||
const rssToggle = screen.getByRole('checkbox');
|
||||
fireEvent.click(rssToggle);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add Indexer' }));
|
||||
|
||||
expect(onSave).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
id: 1,
|
||||
name: 'Prowlarr',
|
||||
priority: 25,
|
||||
seedingTimeMinutes: 0,
|
||||
rssEnabled: false,
|
||||
categories: expect.arrayContaining([3030]),
|
||||
})
|
||||
);
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('validates that at least one category is selected', () => {
|
||||
const onSave = vi.fn();
|
||||
|
||||
render(
|
||||
<IndexerConfigModal
|
||||
isOpen
|
||||
onClose={vi.fn()}
|
||||
mode="add"
|
||||
indexer={{ id: 2, name: 'NoCats', protocol: 'torrent', supportsRss: true }}
|
||||
onSave={onSave}
|
||||
/>
|
||||
);
|
||||
|
||||
const audiobookLabel = screen.getByText('Audiobook');
|
||||
const audiobookRow = audiobookLabel.closest('div')?.parentElement;
|
||||
if (!audiobookRow) {
|
||||
throw new Error('Audiobook row not found');
|
||||
}
|
||||
|
||||
fireEvent.click(within(audiobookRow).getByRole('switch'));
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add Indexer' }));
|
||||
|
||||
expect(screen.getByText('At least one category must be selected')).toBeInTheDocument();
|
||||
expect(onSave).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('forces RSS to false when the indexer does not support RSS', () => {
|
||||
const onSave = vi.fn();
|
||||
const onClose = vi.fn();
|
||||
|
||||
render(
|
||||
<IndexerConfigModal
|
||||
isOpen
|
||||
onClose={onClose}
|
||||
mode="add"
|
||||
indexer={{ id: 3, name: 'NoRSS', protocol: 'torrent', supportsRss: false }}
|
||||
onSave={onSave}
|
||||
/>
|
||||
);
|
||||
|
||||
const rssToggle = screen.getByRole('checkbox');
|
||||
expect(rssToggle).toBeDisabled();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add Indexer' }));
|
||||
|
||||
expect(onSave).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
id: 3,
|
||||
name: 'NoRSS',
|
||||
rssEnabled: false,
|
||||
})
|
||||
);
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* Component: Indexer Management Tests
|
||||
* Documentation: documentation/frontend/components.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { IndexerManagement } from '@/components/admin/indexers/IndexerManagement';
|
||||
|
||||
const fetchWithAuthMock = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('@/lib/utils/api', () => ({
|
||||
fetchWithAuth: fetchWithAuthMock,
|
||||
}));
|
||||
|
||||
vi.mock('@/components/admin/indexers/IndexerConfigModal', () => ({
|
||||
IndexerConfigModal: ({ isOpen, mode, indexer, initialConfig, onSave, onClose }: any) => {
|
||||
if (!isOpen) return null;
|
||||
const priority = initialConfig?.priority ? initialConfig.priority + 1 : 10;
|
||||
return (
|
||||
<div data-testid="indexer-config-modal">
|
||||
<div data-testid="modal-mode">{mode}</div>
|
||||
<button
|
||||
onClick={() =>
|
||||
onSave({
|
||||
id: indexer.id,
|
||||
name: indexer.name,
|
||||
priority,
|
||||
seedingTimeMinutes: 0,
|
||||
rssEnabled: true,
|
||||
categories: [3030],
|
||||
})
|
||||
}
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
<button onClick={onClose}>Close</button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
describe('IndexerManagement', () => {
|
||||
const emptyIndexers: any[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
fetchWithAuthMock.mockReset();
|
||||
});
|
||||
|
||||
it('fetches indexers in wizard mode and adds a configuration', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
success: true,
|
||||
indexers: [
|
||||
{ id: 1, name: 'IndexerA', protocol: 'torrent', supportsRss: true },
|
||||
],
|
||||
}),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const onIndexersChange = vi.fn();
|
||||
|
||||
render(
|
||||
<IndexerManagement
|
||||
prowlarrUrl="http://prowlarr.local"
|
||||
prowlarrApiKey="apikey"
|
||||
mode="wizard"
|
||||
initialIndexers={emptyIndexers}
|
||||
onIndexersChange={onIndexersChange}
|
||||
/>
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Fetch Indexers' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/setup/test-prowlarr', expect.any(Object));
|
||||
});
|
||||
|
||||
expect(fetchWithAuthMock).not.toHaveBeenCalled();
|
||||
expect(screen.getByText('IndexerA')).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add' }));
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save' }));
|
||||
|
||||
await waitFor(() => {
|
||||
const lastCall = onIndexersChange.mock.calls.at(-1)?.[0] as any[] | undefined;
|
||||
expect(lastCall).toHaveLength(1);
|
||||
expect(lastCall?.[0]).toMatchObject({ id: 1, name: 'IndexerA' });
|
||||
});
|
||||
|
||||
expect(screen.getByText('Configured Indexers (1)')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uses authenticated fetch in settings mode', async () => {
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
fetchWithAuthMock.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
success: true,
|
||||
indexers: [
|
||||
{ id: 2, name: 'IndexerB', protocol: 'torrent', supportsRss: false },
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
render(
|
||||
<IndexerManagement
|
||||
prowlarrUrl="http://prowlarr.local"
|
||||
prowlarrApiKey="apikey"
|
||||
mode="settings"
|
||||
initialIndexers={emptyIndexers}
|
||||
/>
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Fetch Indexers' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(fetchWithAuthMock).toHaveBeenCalledWith(
|
||||
'/api/admin/settings/test-prowlarr',
|
||||
expect.objectContaining({ method: 'POST' })
|
||||
);
|
||||
});
|
||||
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
expect(screen.getByText('IndexerB')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('removes a configured indexer after confirmation', async () => {
|
||||
const onIndexersChange = vi.fn();
|
||||
|
||||
render(
|
||||
<IndexerManagement
|
||||
prowlarrUrl="http://prowlarr.local"
|
||||
prowlarrApiKey="apikey"
|
||||
mode="settings"
|
||||
initialIndexers={[
|
||||
{
|
||||
id: 5,
|
||||
name: 'ConfiguredIndexer',
|
||||
priority: 10,
|
||||
seedingTimeMinutes: 0,
|
||||
rssEnabled: true,
|
||||
categories: [3030],
|
||||
},
|
||||
]}
|
||||
onIndexersChange={onIndexersChange}
|
||||
/>
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByTitle('Delete indexer'));
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Remove Indexer' }));
|
||||
|
||||
await waitFor(() => {
|
||||
const lastCall = onIndexersChange.mock.calls.at(-1)?.[0] as any[] | undefined;
|
||||
expect(lastCall).toHaveLength(0);
|
||||
});
|
||||
|
||||
expect(screen.getByText('Configured Indexers (0)')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* Component: Audiobook Card 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';
|
||||
|
||||
const createRequestMock = vi.hoisted(() => vi.fn());
|
||||
const authState = {
|
||||
user: null as null | { id: string; username: string },
|
||||
};
|
||||
|
||||
vi.mock('@/contexts/AuthContext', () => ({
|
||||
useAuth: () => authState,
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/hooks/useRequests', () => ({
|
||||
useCreateRequest: () => ({ createRequest: createRequestMock, isLoading: false }),
|
||||
}));
|
||||
|
||||
vi.mock('@/components/audiobooks/AudiobookDetailsModal', () => ({
|
||||
AudiobookDetailsModal: ({ isOpen }: { isOpen: boolean }) => (
|
||||
<div data-testid="details-modal" data-open={String(isOpen)} />
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock('next/image', () => ({
|
||||
__esModule: true,
|
||||
default: (props: any) => <img {...props} />,
|
||||
}));
|
||||
|
||||
const baseAudiobook = {
|
||||
asin: 'asin-1',
|
||||
title: 'Test Book',
|
||||
author: 'Author',
|
||||
};
|
||||
|
||||
describe('AudiobookCard', () => {
|
||||
beforeEach(() => {
|
||||
authState.user = null;
|
||||
createRequestMock.mockReset();
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('disables requests when no user is logged in', async () => {
|
||||
const { AudiobookCard } = await import('@/components/audiobooks/AudiobookCard');
|
||||
|
||||
render(<AudiobookCard audiobook={baseAudiobook} />);
|
||||
|
||||
const requestButton = screen.getByRole('button', { name: 'Login to Request' });
|
||||
expect(requestButton).toBeDisabled();
|
||||
expect(createRequestMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('creates a request and shows a success toast', async () => {
|
||||
authState.user = { id: 'user-1', username: 'user' };
|
||||
createRequestMock.mockResolvedValueOnce(undefined);
|
||||
|
||||
const onRequestSuccess = vi.fn();
|
||||
const { AudiobookCard } = await import('@/components/audiobooks/AudiobookCard');
|
||||
|
||||
render(<AudiobookCard audiobook={baseAudiobook} onRequestSuccess={onRequestSuccess} />);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Request' }));
|
||||
|
||||
const requestPromise = createRequestMock.mock.results[0]?.value;
|
||||
await act(async () => {
|
||||
await requestPromise;
|
||||
});
|
||||
|
||||
expect(createRequestMock).toHaveBeenCalledWith(baseAudiobook);
|
||||
expect(onRequestSuccess).toHaveBeenCalled();
|
||||
|
||||
expect(screen.getByText(/Request created successfully/)).toBeInTheDocument();
|
||||
|
||||
await act(async () => {
|
||||
vi.advanceTimersByTime(3000);
|
||||
});
|
||||
expect(screen.queryByText(/Request created successfully/)).toBeNull();
|
||||
});
|
||||
|
||||
it('shows in-library state when available', async () => {
|
||||
const { AudiobookCard } = await import('@/components/audiobooks/AudiobookCard');
|
||||
|
||||
render(<AudiobookCard audiobook={{ ...baseAudiobook, isAvailable: true }} />);
|
||||
|
||||
expect(screen.getByText('In Your Library')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens the details modal when the title is clicked', async () => {
|
||||
const { AudiobookCard } = await import('@/components/audiobooks/AudiobookCard');
|
||||
|
||||
render(<AudiobookCard audiobook={baseAudiobook} />);
|
||||
|
||||
expect(screen.getByTestId('details-modal')).toHaveAttribute('data-open', 'false');
|
||||
|
||||
fireEvent.click(screen.getByText('Test Book'));
|
||||
|
||||
expect(screen.getByTestId('details-modal')).toHaveAttribute('data-open', 'true');
|
||||
});
|
||||
|
||||
it('shows processing state for downloaded requests', async () => {
|
||||
const { AudiobookCard } = await import('@/components/audiobooks/AudiobookCard');
|
||||
|
||||
render(
|
||||
<AudiobookCard
|
||||
audiobook={{ ...baseAudiobook, isRequested: true, requestStatus: 'downloaded' }}
|
||||
/>
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button', { name: 'Processing...' });
|
||||
expect(button).toBeDisabled();
|
||||
});
|
||||
|
||||
it('shows pending approval status with requester name', async () => {
|
||||
const { AudiobookCard } = await import('@/components/audiobooks/AudiobookCard');
|
||||
|
||||
render(
|
||||
<AudiobookCard
|
||||
audiobook={{
|
||||
...baseAudiobook,
|
||||
isRequested: true,
|
||||
requestStatus: 'awaiting_approval',
|
||||
requestedByUsername: 'alice',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByRole('button', { name: /Pending Approval \(alice\)/ })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('shows a denied request state', async () => {
|
||||
const { AudiobookCard } = await import('@/components/audiobooks/AudiobookCard');
|
||||
|
||||
render(
|
||||
<AudiobookCard
|
||||
audiobook={{ ...baseAudiobook, isRequested: true, requestStatus: 'denied' }}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Request Denied' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('shows an error when a request fails', async () => {
|
||||
authState.user = { id: 'user-1', username: 'user' };
|
||||
createRequestMock.mockRejectedValueOnce(new Error('Request failed'));
|
||||
|
||||
const { AudiobookCard } = await import('@/components/audiobooks/AudiobookCard');
|
||||
|
||||
render(<AudiobookCard audiobook={baseAudiobook} />);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Request' }));
|
||||
|
||||
const requestPromise = createRequestMock.mock.results[0]?.value;
|
||||
await act(async () => {
|
||||
try {
|
||||
await requestPromise;
|
||||
} catch {
|
||||
// Expected for this test.
|
||||
}
|
||||
});
|
||||
|
||||
expect(screen.getByText('Request failed')).toBeInTheDocument();
|
||||
|
||||
await act(async () => {
|
||||
vi.advanceTimersByTime(5000);
|
||||
});
|
||||
expect(screen.queryByText('Request failed')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,291 @@
|
||||
/**
|
||||
* Component: Audiobook Details Modal 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';
|
||||
|
||||
const useAuthMock = vi.hoisted(() => vi.fn());
|
||||
const useAudiobookDetailsMock = vi.hoisted(() => vi.fn());
|
||||
const createRequestMock = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('@/contexts/AuthContext', () => ({
|
||||
useAuth: () => useAuthMock(),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/hooks/useAudiobooks', () => ({
|
||||
useAudiobookDetails: (asin: string | null) => useAudiobookDetailsMock(asin),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/hooks/useRequests', () => ({
|
||||
useCreateRequest: () => ({ createRequest: createRequestMock, isLoading: false }),
|
||||
}));
|
||||
|
||||
vi.mock('@/components/requests/InteractiveTorrentSearchModal', () => ({
|
||||
InteractiveTorrentSearchModal: ({ isOpen }: { isOpen: boolean }) => (
|
||||
<div data-testid="interactive-modal" data-open={String(isOpen)} />
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock('next/image', () => ({
|
||||
__esModule: true,
|
||||
default: (props: any) => <img {...props} />,
|
||||
}));
|
||||
|
||||
const audiobookDetails = {
|
||||
asin: 'ASIN123',
|
||||
title: 'Detail Book',
|
||||
author: 'Detail Author',
|
||||
description: 'Summary',
|
||||
rating: 4.2,
|
||||
durationMinutes: 320,
|
||||
releaseDate: '2023-01-01',
|
||||
genres: ['Fantasy'],
|
||||
};
|
||||
|
||||
describe('AudiobookDetailsModal', () => {
|
||||
beforeEach(() => {
|
||||
useAuthMock.mockReturnValue({ user: { id: 'user-1', username: 'user' } });
|
||||
useAudiobookDetailsMock.mockReturnValue({
|
||||
audiobook: audiobookDetails,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
createRequestMock.mockReset();
|
||||
Object.assign(navigator, {
|
||||
clipboard: {
|
||||
writeText: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('renders audiobook details and closes when requested', async () => {
|
||||
const onClose = vi.fn();
|
||||
const { AudiobookDetailsModal } = await import('@/components/audiobooks/AudiobookDetailsModal');
|
||||
|
||||
render(
|
||||
<AudiobookDetailsModal
|
||||
asin="ASIN123"
|
||||
isOpen={true}
|
||||
onClose={onClose}
|
||||
/>
|
||||
);
|
||||
|
||||
await act(async () => {});
|
||||
expect(screen.getByText('Detail Book')).toBeInTheDocument();
|
||||
expect(document.body.style.overflow).toBe('hidden');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Close modal' }));
|
||||
expect(onClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('creates requests and auto-closes after success', async () => {
|
||||
vi.useFakeTimers();
|
||||
createRequestMock.mockResolvedValueOnce(undefined);
|
||||
const onClose = vi.fn();
|
||||
const onRequestSuccess = vi.fn();
|
||||
const { AudiobookDetailsModal } = await import('@/components/audiobooks/AudiobookDetailsModal');
|
||||
|
||||
render(
|
||||
<AudiobookDetailsModal
|
||||
asin="ASIN123"
|
||||
isOpen={true}
|
||||
onClose={onClose}
|
||||
onRequestSuccess={onRequestSuccess}
|
||||
/>
|
||||
);
|
||||
|
||||
await act(async () => {});
|
||||
const requestButton = screen.getByRole('button', { name: 'Request Audiobook' });
|
||||
fireEvent.click(requestButton);
|
||||
|
||||
const requestPromise = createRequestMock.mock.results[0]?.value;
|
||||
await act(async () => {
|
||||
await requestPromise;
|
||||
});
|
||||
|
||||
expect(onRequestSuccess).toHaveBeenCalled();
|
||||
expect(screen.getByText(/Request created successfully/)).toBeInTheDocument();
|
||||
|
||||
await act(async () => {
|
||||
vi.advanceTimersByTime(2000);
|
||||
});
|
||||
|
||||
expect(onClose).toHaveBeenCalled();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('copies the ASIN to the clipboard', async () => {
|
||||
const { AudiobookDetailsModal } = await import('@/components/audiobooks/AudiobookDetailsModal');
|
||||
|
||||
render(
|
||||
<AudiobookDetailsModal
|
||||
asin="ASIN123"
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
);
|
||||
|
||||
await act(async () => {});
|
||||
const asinButton = screen.getByText('ASIN123');
|
||||
await act(async () => {
|
||||
fireEvent.click(asinButton.closest('button') as HTMLButtonElement);
|
||||
});
|
||||
|
||||
expect(navigator.clipboard.writeText).toHaveBeenCalledWith('ASIN123');
|
||||
});
|
||||
|
||||
it('shows an error state when details fail to load', async () => {
|
||||
useAudiobookDetailsMock.mockReturnValue({
|
||||
audiobook: null,
|
||||
isLoading: false,
|
||||
error: 'boom',
|
||||
});
|
||||
const { AudiobookDetailsModal } = await import('@/components/audiobooks/AudiobookDetailsModal');
|
||||
|
||||
render(
|
||||
<AudiobookDetailsModal
|
||||
asin="ASIN123"
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
);
|
||||
|
||||
await act(async () => {});
|
||||
expect(screen.getByText('Failed to load audiobook details')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows availability state and hides interactive search when available', async () => {
|
||||
const { AudiobookDetailsModal } = await import('@/components/audiobooks/AudiobookDetailsModal');
|
||||
|
||||
render(
|
||||
<AudiobookDetailsModal
|
||||
asin="ASIN123"
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
isAvailable={true}
|
||||
/>
|
||||
);
|
||||
|
||||
await act(async () => {});
|
||||
expect(screen.getByText('Available in Your Library')).toBeInTheDocument();
|
||||
expect(screen.queryByLabelText('Interactive Search')).toBeNull();
|
||||
});
|
||||
|
||||
it('shows pending approval status with requester name', async () => {
|
||||
const { AudiobookDetailsModal } = await import('@/components/audiobooks/AudiobookDetailsModal');
|
||||
|
||||
render(
|
||||
<AudiobookDetailsModal
|
||||
asin="ASIN123"
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
isRequested={true}
|
||||
requestStatus="awaiting_approval"
|
||||
requestedByUsername="alice"
|
||||
/>
|
||||
);
|
||||
|
||||
await act(async () => {});
|
||||
expect(screen.getByRole('button', { name: /Pending Approval \(alice\)/ })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('shows a denied request state', async () => {
|
||||
const { AudiobookDetailsModal } = await import('@/components/audiobooks/AudiobookDetailsModal');
|
||||
|
||||
render(
|
||||
<AudiobookDetailsModal
|
||||
asin="ASIN123"
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
isRequested={true}
|
||||
requestStatus="denied"
|
||||
/>
|
||||
);
|
||||
|
||||
await act(async () => {});
|
||||
expect(screen.getByRole('button', { name: 'Request Denied' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('shows Not Found when rating is missing', async () => {
|
||||
useAudiobookDetailsMock.mockReturnValue({
|
||||
audiobook: { ...audiobookDetails, rating: 0 },
|
||||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
const { AudiobookDetailsModal } = await import('@/components/audiobooks/AudiobookDetailsModal');
|
||||
|
||||
render(
|
||||
<AudiobookDetailsModal
|
||||
asin="ASIN123"
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
);
|
||||
|
||||
await act(async () => {});
|
||||
expect(screen.getByText('Not Found')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens interactive search when requested', async () => {
|
||||
const { AudiobookDetailsModal } = await import('@/components/audiobooks/AudiobookDetailsModal');
|
||||
|
||||
render(
|
||||
<AudiobookDetailsModal
|
||||
asin="ASIN123"
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
);
|
||||
|
||||
await act(async () => {});
|
||||
|
||||
expect(screen.queryByTestId('interactive-modal')).toBeNull();
|
||||
|
||||
fireEvent.click(screen.getByLabelText('Interactive Search'));
|
||||
|
||||
expect(screen.getByTestId('interactive-modal')).toHaveAttribute('data-open', 'true');
|
||||
});
|
||||
|
||||
it('shows request error and clears it after timeout', async () => {
|
||||
vi.useFakeTimers();
|
||||
createRequestMock.mockRejectedValueOnce(new Error('Request failed'));
|
||||
const { AudiobookDetailsModal } = await import('@/components/audiobooks/AudiobookDetailsModal');
|
||||
|
||||
render(
|
||||
<AudiobookDetailsModal
|
||||
asin="ASIN123"
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
);
|
||||
|
||||
await act(async () => {});
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Request Audiobook' }));
|
||||
|
||||
const requestPromise = createRequestMock.mock.results[0]?.value;
|
||||
await act(async () => {
|
||||
try {
|
||||
await requestPromise;
|
||||
} catch {
|
||||
// Expected for this test.
|
||||
}
|
||||
});
|
||||
|
||||
expect(screen.getByText('Request failed')).toBeInTheDocument();
|
||||
|
||||
await act(async () => {
|
||||
vi.advanceTimersByTime(5000);
|
||||
});
|
||||
|
||||
expect(screen.queryByText('Request failed')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Component: Audiobook Grid Tests
|
||||
* Documentation: documentation/frontend/components.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import React from 'react';
|
||||
import path from 'path';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const mockAudiobookCard = () => {
|
||||
vi.doMock(path.resolve('src/components/audiobooks/AudiobookCard.tsx'), () => ({
|
||||
AudiobookCard: ({ audiobook }: { audiobook: any }) => (
|
||||
<div data-testid="audiobook-card">{audiobook.asin}</div>
|
||||
),
|
||||
}));
|
||||
};
|
||||
|
||||
describe('AudiobookGrid', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
mockAudiobookCard();
|
||||
});
|
||||
|
||||
it('renders skeleton cards when loading', async () => {
|
||||
const { AudiobookGrid } = await import('@/components/audiobooks/AudiobookGrid');
|
||||
|
||||
const { container } = render(<AudiobookGrid audiobooks={[]} isLoading={true} />);
|
||||
|
||||
expect(container.querySelectorAll('.animate-pulse')).toHaveLength(8);
|
||||
});
|
||||
|
||||
it('shows the empty message when there are no results', async () => {
|
||||
const { AudiobookGrid } = await import('@/components/audiobooks/AudiobookGrid');
|
||||
|
||||
render(<AudiobookGrid audiobooks={[]} isLoading={false} emptyMessage="Nothing found" />);
|
||||
|
||||
expect(screen.getByText('Nothing found')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies grid classes based on card size', async () => {
|
||||
const { AudiobookGrid } = await import('@/components/audiobooks/AudiobookGrid');
|
||||
|
||||
const { container } = render(
|
||||
<AudiobookGrid
|
||||
audiobooks={[{ asin: 'a1', title: 'Book', author: 'Author' }]}
|
||||
cardSize={9}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(container.querySelector('div')?.className).toContain('grid-cols-1');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* Component: Protected Route Component Tests
|
||||
* Documentation: documentation/frontend/routing-auth.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { beforeAll, describe, expect, it } from 'vitest';
|
||||
import { screen, waitFor } from '@testing-library/react';
|
||||
import { renderWithProviders } from '../../helpers/render';
|
||||
import { routerMock } from '../../helpers/mock-next-navigation';
|
||||
|
||||
describe('ProtectedRoute', () => {
|
||||
let ProtectedRoute: typeof import('@/components/auth/ProtectedRoute').ProtectedRoute;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ ProtectedRoute } = await import('@/components/auth/ProtectedRoute'));
|
||||
});
|
||||
|
||||
it('shows loading state while auth is initializing', async () => {
|
||||
renderWithProviders(
|
||||
<ProtectedRoute>
|
||||
<div>Protected Content</div>
|
||||
</ProtectedRoute>,
|
||||
{ auth: { isLoading: true } }
|
||||
);
|
||||
|
||||
expect(screen.getByText(/Loading/i)).toBeInTheDocument();
|
||||
expect(screen.queryByText('Protected Content')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('redirects unauthenticated users to login with return URL', async () => {
|
||||
renderWithProviders(
|
||||
<ProtectedRoute>
|
||||
<div>Protected Content</div>
|
||||
</ProtectedRoute>,
|
||||
{ auth: { user: null, isLoading: false }, pathname: '/requests' }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/login?redirect=%2Frequests');
|
||||
});
|
||||
expect(screen.queryByText('Protected Content')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('redirects non-admin users when admin access is required', async () => {
|
||||
renderWithProviders(
|
||||
<ProtectedRoute requireAdmin>
|
||||
<div>Admin Content</div>
|
||||
</ProtectedRoute>,
|
||||
{
|
||||
auth: {
|
||||
user: {
|
||||
id: 'user-1',
|
||||
plexId: 'plex-1',
|
||||
username: 'reader',
|
||||
role: 'user',
|
||||
},
|
||||
isLoading: false,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/');
|
||||
});
|
||||
expect(screen.queryByText('Admin Content')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders children for authenticated admins', async () => {
|
||||
renderWithProviders(
|
||||
<ProtectedRoute requireAdmin>
|
||||
<div>Admin Content</div>
|
||||
</ProtectedRoute>,
|
||||
{
|
||||
auth: {
|
||||
user: {
|
||||
id: 'admin-1',
|
||||
plexId: 'plex-1',
|
||||
username: 'admin',
|
||||
role: 'admin',
|
||||
},
|
||||
isLoading: false,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
expect(screen.getByText('Admin Content')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* Component: BookDate Book Picker Modal Tests
|
||||
* Documentation: documentation/features/bookdate.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import React from 'react';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const books = [
|
||||
{ id: 'book-1', title: 'First Book', author: 'Author One', coverUrl: null },
|
||||
{ id: 'book-2', title: 'Second Book', author: 'Author Two', coverUrl: null },
|
||||
];
|
||||
|
||||
describe('BookPickerModal', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
it('loads books and confirms the selection', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ books }),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
localStorage.setItem('accessToken', 'token-123');
|
||||
const onConfirm = vi.fn();
|
||||
const onClose = vi.fn();
|
||||
const { BookPickerModal } = await import('@/components/bookdate/BookPickerModal');
|
||||
|
||||
render(
|
||||
<BookPickerModal
|
||||
isOpen={true}
|
||||
onClose={onClose}
|
||||
selectedIds={[]}
|
||||
onConfirm={onConfirm}
|
||||
maxSelection={5}
|
||||
/>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/bookdate/library', {
|
||||
headers: { Authorization: 'Bearer token-123' },
|
||||
});
|
||||
});
|
||||
|
||||
const firstBookButton = await screen.findByRole('button', { name: /First Book/ });
|
||||
fireEvent.click(firstBookButton);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Confirm Selection/ }));
|
||||
|
||||
expect(onConfirm).toHaveBeenCalledWith(['book-1']);
|
||||
expect(onClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('disables additional selections once the max is reached', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ books }),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
localStorage.setItem('accessToken', 'token-456');
|
||||
const { BookPickerModal } = await import('@/components/bookdate/BookPickerModal');
|
||||
|
||||
render(
|
||||
<BookPickerModal
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
selectedIds={[]}
|
||||
onConfirm={vi.fn()}
|
||||
maxSelection={1}
|
||||
/>
|
||||
);
|
||||
|
||||
const firstBookButton = await screen.findByRole('button', { name: /First Book/ });
|
||||
fireEvent.click(firstBookButton);
|
||||
|
||||
expect(screen.getByText(/Maximum reached/)).toBeInTheDocument();
|
||||
|
||||
const secondBookButton = screen.getByRole('button', { name: /Second Book/ });
|
||||
expect(secondBookButton).toBeDisabled();
|
||||
});
|
||||
|
||||
it('shows an error when loading books fails', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
json: async () => ({}),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const { BookPickerModal } = await import('@/components/bookdate/BookPickerModal');
|
||||
|
||||
render(
|
||||
<BookPickerModal
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
selectedIds={[]}
|
||||
onConfirm={vi.fn()}
|
||||
maxSelection={5}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(await screen.findByText('Failed to load library books')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows an empty search state when no books match', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ books }),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const { BookPickerModal } = await import('@/components/bookdate/BookPickerModal');
|
||||
|
||||
render(
|
||||
<BookPickerModal
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
selectedIds={[]}
|
||||
onConfirm={vi.fn()}
|
||||
maxSelection={5}
|
||||
/>
|
||||
);
|
||||
|
||||
await screen.findByRole('button', { name: /First Book/ });
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('Search books...'), { target: { value: 'missing' } });
|
||||
|
||||
expect(screen.getByText('No books match your search')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('clears selection and disables confirm', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ books }),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const { BookPickerModal } = await import('@/components/bookdate/BookPickerModal');
|
||||
|
||||
render(
|
||||
<BookPickerModal
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
selectedIds={['book-1']}
|
||||
onConfirm={vi.fn()}
|
||||
maxSelection={5}
|
||||
/>
|
||||
);
|
||||
|
||||
await screen.findByRole('button', { name: /First Book/ });
|
||||
|
||||
const clearButton = screen.getByRole('button', { name: 'Clear Selection' });
|
||||
fireEvent.click(clearButton);
|
||||
|
||||
expect(screen.getByRole('button', { name: /Confirm Selection/ })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* Component: BookDate Card Stack Tests
|
||||
* Documentation: documentation/features/bookdate-animations.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import React from 'react';
|
||||
import { act, fireEvent, render, screen } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('@/components/bookdate/RecommendationCard', () => ({
|
||||
RecommendationCard: ({
|
||||
recommendation,
|
||||
onSwipe,
|
||||
stackPosition,
|
||||
isDraggable,
|
||||
}: {
|
||||
recommendation: { id: string; title: string };
|
||||
onSwipe: (action: 'left' | 'right' | 'up') => void;
|
||||
stackPosition: number;
|
||||
isDraggable: boolean;
|
||||
}) => (
|
||||
<button
|
||||
data-testid={`card-${recommendation.id}`}
|
||||
data-stack={stackPosition}
|
||||
data-draggable={String(isDraggable)}
|
||||
onClick={() => onSwipe('left')}
|
||||
>
|
||||
{recommendation.title}
|
||||
</button>
|
||||
),
|
||||
}));
|
||||
|
||||
const recommendations = [
|
||||
{ id: 'rec-1', title: 'Rec One' },
|
||||
{ id: 'rec-2', title: 'Rec Two' },
|
||||
{ id: 'rec-3', title: 'Rec Three' },
|
||||
{ id: 'rec-4', title: 'Rec Four' },
|
||||
];
|
||||
|
||||
describe('CardStack', () => {
|
||||
it('renders up to three cards and only the top card is draggable', async () => {
|
||||
const { CardStack } = await import('@/components/bookdate/CardStack');
|
||||
|
||||
render(
|
||||
<CardStack
|
||||
recommendations={recommendations}
|
||||
currentIndex={0}
|
||||
onSwipe={vi.fn()}
|
||||
onSwipeComplete={vi.fn()}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('card-rec-1')).toHaveAttribute('data-stack', '0');
|
||||
expect(screen.getByTestId('card-rec-1')).toHaveAttribute('data-draggable', 'true');
|
||||
expect(screen.getByTestId('card-rec-2')).toHaveAttribute('data-stack', '1');
|
||||
expect(screen.getByTestId('card-rec-3')).toHaveAttribute('data-stack', '2');
|
||||
expect(screen.queryByTestId('card-rec-4')).toBeNull();
|
||||
});
|
||||
|
||||
it('locks swipes during animations and calls onSwipeComplete', async () => {
|
||||
vi.useFakeTimers();
|
||||
const onSwipe = vi.fn();
|
||||
const onSwipeComplete = vi.fn();
|
||||
const { CardStack } = await import('@/components/bookdate/CardStack');
|
||||
|
||||
render(
|
||||
<CardStack
|
||||
recommendations={recommendations}
|
||||
currentIndex={0}
|
||||
onSwipe={onSwipe}
|
||||
onSwipeComplete={onSwipeComplete}
|
||||
/>
|
||||
);
|
||||
|
||||
const topCard = screen.getByTestId('card-rec-1');
|
||||
fireEvent.click(topCard);
|
||||
fireEvent.click(topCard);
|
||||
|
||||
expect(onSwipe).toHaveBeenCalledTimes(1);
|
||||
|
||||
await act(async () => {
|
||||
vi.advanceTimersByTime(750);
|
||||
});
|
||||
expect(onSwipeComplete).toHaveBeenCalledTimes(1);
|
||||
vi.useRealTimers();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Component: BookDate Loading Screen Tests
|
||||
* Documentation: documentation/features/bookdate.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import React from 'react';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('@/components/layout/Header', () => ({
|
||||
Header: () => <div data-testid="header" />,
|
||||
}));
|
||||
|
||||
describe('LoadingScreen', () => {
|
||||
it('renders the loading message and header', async () => {
|
||||
const { LoadingScreen } = await import('@/components/bookdate/LoadingScreen');
|
||||
|
||||
render(<LoadingScreen />);
|
||||
|
||||
expect(screen.getByTestId('header')).toBeInTheDocument();
|
||||
expect(screen.getByText('Finding your next great listen...')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* Component: BookDate Recommendation Card Tests
|
||||
* Documentation: documentation/features/bookdate.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import React from 'react';
|
||||
import { act, fireEvent, render, screen } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const swipeHandlers: {
|
||||
onSwiping?: (eventData: { deltaX: number; deltaY: number }) => void;
|
||||
onSwiped?: (eventData: { deltaX: number; deltaY: number }) => void;
|
||||
} = {};
|
||||
|
||||
vi.mock('react-swipeable', () => ({
|
||||
useSwipeable: (handlers: any) => {
|
||||
swipeHandlers.onSwiping = handlers.onSwiping;
|
||||
swipeHandlers.onSwiped = handlers.onSwiped;
|
||||
return {};
|
||||
},
|
||||
}));
|
||||
|
||||
const recommendation = {
|
||||
title: 'Sample Book',
|
||||
author: 'Sample Author',
|
||||
narrator: 'Sample Narrator',
|
||||
rating: 4.5,
|
||||
description: 'A sample description',
|
||||
aiReason: 'Because it matches your tastes.',
|
||||
};
|
||||
|
||||
describe('RecommendationCard', () => {
|
||||
beforeEach(() => {
|
||||
swipeHandlers.onSwiping = undefined;
|
||||
swipeHandlers.onSwiped = undefined;
|
||||
});
|
||||
|
||||
it('shows the request toast and triggers a request action', async () => {
|
||||
const onSwipe = vi.fn();
|
||||
const { RecommendationCard } = await import('@/components/bookdate/RecommendationCard');
|
||||
|
||||
render(<RecommendationCard recommendation={recommendation} onSwipe={onSwipe} />);
|
||||
|
||||
const requestButtons = screen.getAllByRole('button', { name: /Request/ });
|
||||
fireEvent.click(requestButtons[0]);
|
||||
|
||||
expect(screen.getByText('Request "Sample Book"?')).toBeInTheDocument();
|
||||
const toastRequestButtons = screen.getAllByRole('button', { name: /Request/ });
|
||||
fireEvent.click(toastRequestButtons[toastRequestButtons.length - 1]);
|
||||
|
||||
expect(onSwipe).toHaveBeenCalledWith('right', false);
|
||||
});
|
||||
|
||||
it('marks a recommendation as liked from the toast', async () => {
|
||||
const onSwipe = vi.fn();
|
||||
const { RecommendationCard } = await import('@/components/bookdate/RecommendationCard');
|
||||
|
||||
render(<RecommendationCard recommendation={recommendation} onSwipe={onSwipe} />);
|
||||
|
||||
const requestButtons = screen.getAllByRole('button', { name: /Request/ });
|
||||
fireEvent.click(requestButtons[0]);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Mark as Liked' }));
|
||||
|
||||
expect(onSwipe).toHaveBeenCalledWith('right', true);
|
||||
});
|
||||
|
||||
it('triggers dislike and dismiss actions from desktop buttons', async () => {
|
||||
const onSwipe = vi.fn();
|
||||
const { RecommendationCard } = await import('@/components/bookdate/RecommendationCard');
|
||||
|
||||
render(<RecommendationCard recommendation={recommendation} onSwipe={onSwipe} />);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Not Interested/ }));
|
||||
fireEvent.click(screen.getByRole('button', { name: /Dismiss/ }));
|
||||
|
||||
expect(onSwipe).toHaveBeenCalledWith('left');
|
||||
expect(onSwipe).toHaveBeenCalledWith('up');
|
||||
});
|
||||
|
||||
it('shows drag overlays based on swipe direction', async () => {
|
||||
const onSwipe = vi.fn();
|
||||
const { RecommendationCard } = await import('@/components/bookdate/RecommendationCard');
|
||||
|
||||
render(<RecommendationCard recommendation={recommendation} onSwipe={onSwipe} />);
|
||||
|
||||
act(() => {
|
||||
swipeHandlers.onSwiping?.({ deltaX: -80, deltaY: 0 });
|
||||
});
|
||||
|
||||
expect(screen.getByText('Dislike')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('triggers an upward swipe from gesture handling', async () => {
|
||||
const onSwipe = vi.fn();
|
||||
const { RecommendationCard } = await import('@/components/bookdate/RecommendationCard');
|
||||
|
||||
render(<RecommendationCard recommendation={recommendation} onSwipe={onSwipe} />);
|
||||
|
||||
act(() => {
|
||||
swipeHandlers.onSwiped?.({ deltaX: 0, deltaY: -150 });
|
||||
});
|
||||
|
||||
expect(onSwipe).toHaveBeenCalledWith('up');
|
||||
});
|
||||
|
||||
it('ignores swipe gestures when not draggable', async () => {
|
||||
const onSwipe = vi.fn();
|
||||
const { RecommendationCard } = await import('@/components/bookdate/RecommendationCard');
|
||||
|
||||
render(
|
||||
<RecommendationCard recommendation={recommendation} onSwipe={onSwipe} isDraggable={false} />
|
||||
);
|
||||
|
||||
act(() => {
|
||||
swipeHandlers.onSwiped?.({ deltaX: 150, deltaY: 0 });
|
||||
});
|
||||
|
||||
expect(onSwipe).not.toHaveBeenCalled();
|
||||
expect(screen.queryByText(/Request "Sample Book"/)).toBeNull();
|
||||
});
|
||||
|
||||
it('hides desktop actions when not the top card', async () => {
|
||||
const onSwipe = vi.fn();
|
||||
const { RecommendationCard } = await import('@/components/bookdate/RecommendationCard');
|
||||
|
||||
render(
|
||||
<RecommendationCard recommendation={recommendation} onSwipe={onSwipe} stackPosition={1} />
|
||||
);
|
||||
|
||||
expect(screen.queryByRole('button', { name: /Not Interested/ })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,205 @@
|
||||
/**
|
||||
* Component: BookDate Settings Widget Tests
|
||||
* Documentation: documentation/features/bookdate.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import React from 'react';
|
||||
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('@/components/bookdate/BookPickerModal', () => ({
|
||||
BookPickerModal: ({ isOpen, onConfirm }: { isOpen: boolean; onConfirm: (ids: string[]) => void }) =>
|
||||
isOpen ? (
|
||||
<div data-testid="book-picker">
|
||||
<button onClick={() => onConfirm(['book-1'])}>Select Book</button>
|
||||
</div>
|
||||
) : null,
|
||||
}));
|
||||
|
||||
describe('SettingsWidget', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
it('loads preferences and populates the form', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
libraryScope: 'rated',
|
||||
favoriteBookIds: ['book-1'],
|
||||
customPrompt: 'Custom prompt',
|
||||
backendCapabilities: { supportsRatings: true },
|
||||
}),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
localStorage.setItem('accessToken', 'token-789');
|
||||
const { SettingsWidget } = await import('@/components/bookdate/SettingsWidget');
|
||||
|
||||
render(<SettingsWidget isOpen={true} onClose={vi.fn()} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/bookdate/preferences', {
|
||||
headers: { Authorization: 'Bearer token-789' },
|
||||
});
|
||||
});
|
||||
|
||||
const ratedRadio = await screen.findByRole('radio', { name: /Rated Books Only/ });
|
||||
expect(ratedRadio).toBeChecked();
|
||||
expect(screen.getByDisplayValue('Custom prompt')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('requires favorites selection before saving', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
libraryScope: 'full',
|
||||
favoriteBookIds: [],
|
||||
customPrompt: '',
|
||||
backendCapabilities: { supportsRatings: true },
|
||||
}),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
localStorage.setItem('accessToken', 'token-000');
|
||||
const { SettingsWidget } = await import('@/components/bookdate/SettingsWidget');
|
||||
|
||||
render(<SettingsWidget isOpen={true} onClose={vi.fn()} />);
|
||||
|
||||
const favoritesRadio = await screen.findByRole('radio', { name: /Pick my favorites/ });
|
||||
fireEvent.click(favoritesRadio);
|
||||
fireEvent.click(screen.getByRole('button', { name: /Save Preferences/ }));
|
||||
|
||||
expect(await screen.findByText('Please select at least 1 favorite book')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('saves onboarding preferences and calls completion handlers', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
libraryScope: 'full',
|
||||
favoriteBookIds: [],
|
||||
customPrompt: '',
|
||||
backendCapabilities: { supportsRatings: true },
|
||||
}),
|
||||
})
|
||||
.mockResolvedValueOnce({ ok: true });
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
localStorage.setItem('accessToken', 'token-onboarding');
|
||||
const onClose = vi.fn();
|
||||
const onOnboardingComplete = vi.fn();
|
||||
const { SettingsWidget } = await import('@/components/bookdate/SettingsWidget');
|
||||
|
||||
render(
|
||||
<SettingsWidget
|
||||
isOpen={true}
|
||||
onClose={onClose}
|
||||
isOnboarding={true}
|
||||
onOnboardingComplete={onOnboardingComplete}
|
||||
/>
|
||||
);
|
||||
|
||||
const letsGoButton = await screen.findByRole('button', { name: "Let's Go!" });
|
||||
vi.useFakeTimers();
|
||||
fireEvent.click(letsGoButton);
|
||||
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
|
||||
const requestBody = JSON.parse(fetchMock.mock.calls[1][1].body as string);
|
||||
expect(requestBody.onboardingComplete).toBe(true);
|
||||
expect(requestBody.customPrompt).toBeNull();
|
||||
expect(requestBody.libraryScope).toBe('full');
|
||||
|
||||
await act(async () => {
|
||||
vi.advanceTimersByTime(500);
|
||||
});
|
||||
|
||||
expect(onOnboardingComplete).toHaveBeenCalled();
|
||||
expect(onClose).toHaveBeenCalled();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('hides rated scope when backend does not support ratings', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
libraryScope: 'full',
|
||||
favoriteBookIds: [],
|
||||
customPrompt: '',
|
||||
backendCapabilities: { supportsRatings: false },
|
||||
}),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
localStorage.setItem('accessToken', 'token-no-ratings');
|
||||
const { SettingsWidget } = await import('@/components/bookdate/SettingsWidget');
|
||||
|
||||
render(<SettingsWidget isOpen={true} onClose={vi.fn()} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(fetchMock).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
expect(screen.queryByRole('radio', { name: /Rated Books Only/ })).toBeNull();
|
||||
});
|
||||
|
||||
it('shows an error when loading preferences fails', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
json: async () => ({}),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
localStorage.setItem('accessToken', 'token-fail');
|
||||
const { SettingsWidget } = await import('@/components/bookdate/SettingsWidget');
|
||||
|
||||
render(<SettingsWidget isOpen={true} onClose={vi.fn()} />);
|
||||
|
||||
expect(await screen.findByText('Failed to load preferences')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('saves preferences and clears success message after delay', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
libraryScope: 'full',
|
||||
favoriteBookIds: [],
|
||||
customPrompt: '',
|
||||
backendCapabilities: { supportsRatings: true },
|
||||
}),
|
||||
})
|
||||
.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
localStorage.setItem('accessToken', 'token-save');
|
||||
const { SettingsWidget } = await import('@/components/bookdate/SettingsWidget');
|
||||
|
||||
render(<SettingsWidget isOpen={true} onClose={vi.fn()} />);
|
||||
|
||||
const promptInput = await screen.findByLabelText(/Special Requests/);
|
||||
fireEvent.change(promptInput, { target: { value: ' trimmed ' } });
|
||||
|
||||
vi.useFakeTimers();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save Preferences' }));
|
||||
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
const requestBody = JSON.parse(fetchMock.mock.calls[1][1].body as string);
|
||||
expect(requestBody.customPrompt).toBe('trimmed');
|
||||
expect(requestBody.onboardingComplete).toBeUndefined();
|
||||
|
||||
expect(screen.getByText('Preferences saved successfully!')).toBeInTheDocument();
|
||||
|
||||
await act(async () => {
|
||||
vi.advanceTimersByTime(3000);
|
||||
});
|
||||
|
||||
expect(screen.queryByText('Preferences saved successfully!')).toBeNull();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,226 @@
|
||||
/**
|
||||
* Component: Header Component Tests
|
||||
* Documentation: documentation/frontend/components.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { renderWithProviders } from '../../helpers/render';
|
||||
|
||||
describe('Header', () => {
|
||||
let Header: typeof import('@/components/layout/Header').Header;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ Header } = await import('@/components/layout/Header'));
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('renders login button and opens Plex auth window', async () => {
|
||||
const fetchMock = vi.fn().mockImplementation((input: RequestInfo) => {
|
||||
if (input === '/api/version') {
|
||||
return Promise.resolve({
|
||||
json: vi.fn().mockResolvedValue({ version: 'v.test' }),
|
||||
});
|
||||
}
|
||||
|
||||
return Promise.resolve({
|
||||
json: vi.fn().mockResolvedValue({ success: true, authUrl: 'https://plex.example/login' }),
|
||||
});
|
||||
});
|
||||
const openMock = vi.spyOn(window, 'open').mockImplementation(() => null);
|
||||
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
renderWithProviders(<Header />, { auth: { user: null, isLoading: false } });
|
||||
|
||||
const loginButton = screen.getByRole('button', { name: /login with plex/i });
|
||||
await userEvent.click(loginButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/auth/plex/login', { method: 'POST' });
|
||||
});
|
||||
expect(openMock).toHaveBeenCalledWith(
|
||||
'https://plex.example/login',
|
||||
'plex-auth',
|
||||
'width=600,height=700'
|
||||
);
|
||||
});
|
||||
|
||||
it('renders admin navigation and user menu actions for local users', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
json: vi.fn().mockResolvedValue({ version: 'v.test' }),
|
||||
});
|
||||
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
renderWithProviders(<Header />, {
|
||||
auth: {
|
||||
user: {
|
||||
id: 'admin-1',
|
||||
plexId: 'plex-1',
|
||||
username: 'admin',
|
||||
role: 'admin',
|
||||
authProvider: 'local',
|
||||
},
|
||||
isLoading: false,
|
||||
},
|
||||
});
|
||||
|
||||
expect(screen.getByRole('link', { name: 'Admin' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('link', { name: 'My Requests' })).toBeInTheDocument();
|
||||
|
||||
const userButton = screen.getByText('admin').closest('button');
|
||||
expect(userButton).not.toBeNull();
|
||||
await userEvent.click(userButton as HTMLButtonElement);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Change Password')).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByText('Logout')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows BookDate link and avatar when BookDate is enabled', async () => {
|
||||
localStorage.setItem('accessToken', 'token');
|
||||
const fetchMock = vi.fn().mockImplementation((input: RequestInfo) => {
|
||||
if (input === '/api/version') {
|
||||
return Promise.resolve({
|
||||
json: vi.fn().mockResolvedValue({ version: 'v.test' }),
|
||||
});
|
||||
}
|
||||
if (input === '/api/bookdate/config') {
|
||||
return Promise.resolve({
|
||||
json: vi.fn().mockResolvedValue({
|
||||
config: { isVerified: true, isEnabled: true },
|
||||
}),
|
||||
});
|
||||
}
|
||||
return Promise.resolve({
|
||||
json: vi.fn().mockResolvedValue({}),
|
||||
});
|
||||
});
|
||||
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
renderWithProviders(<Header />, {
|
||||
auth: {
|
||||
user: {
|
||||
id: 'user-1',
|
||||
plexId: 'plex-1',
|
||||
username: 'reader',
|
||||
role: 'user',
|
||||
avatarUrl: '/avatar.png',
|
||||
},
|
||||
isLoading: false,
|
||||
},
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('link', { name: 'BookDate' })).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByAltText('reader')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('logs out from the user menu and shows initials fallback', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
json: vi.fn().mockResolvedValue({ version: 'v.test' }),
|
||||
});
|
||||
const logoutMock = vi.fn();
|
||||
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
renderWithProviders(<Header />, {
|
||||
auth: {
|
||||
user: {
|
||||
id: 'user-2',
|
||||
plexId: 'plex-2',
|
||||
username: 'alice',
|
||||
role: 'user',
|
||||
authProvider: 'plex',
|
||||
},
|
||||
logout: logoutMock,
|
||||
isLoading: false,
|
||||
},
|
||||
});
|
||||
|
||||
expect(screen.getByText(/^A$/)).toBeInTheDocument();
|
||||
|
||||
const userButton = screen.getByText('alice').closest('button');
|
||||
expect(userButton).not.toBeNull();
|
||||
await userEvent.click(userButton as HTMLButtonElement);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Logout')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Logout'));
|
||||
|
||||
expect(logoutMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('toggles the mobile menu and closes after navigation', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
json: vi.fn().mockResolvedValue({ version: 'v.test' }),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
renderWithProviders(<Header />, { auth: { user: null, isLoading: false } });
|
||||
|
||||
const initialHomeLinks = screen.getAllByRole('link', { name: 'Home' }).length;
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Toggle menu' }));
|
||||
|
||||
const openHomeLinks = screen.getAllByRole('link', { name: 'Home' });
|
||||
expect(openHomeLinks).toHaveLength(initialHomeLinks + 1);
|
||||
|
||||
await userEvent.click(openHomeLinks[openHomeLinks.length - 1]);
|
||||
expect(screen.getAllByRole('link', { name: 'Home' })).toHaveLength(initialHomeLinks);
|
||||
});
|
||||
|
||||
it('hides BookDate when config check fails', async () => {
|
||||
localStorage.setItem('accessToken', 'token');
|
||||
const errorMock = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
const fetchMock = vi.fn().mockImplementation((input: RequestInfo) => {
|
||||
if (input === '/api/version') {
|
||||
return Promise.resolve({
|
||||
json: vi.fn().mockResolvedValue({ version: 'v.test' }),
|
||||
});
|
||||
}
|
||||
if (input === '/api/bookdate/config') {
|
||||
return Promise.reject(new Error('boom'));
|
||||
}
|
||||
return Promise.resolve({
|
||||
json: vi.fn().mockResolvedValue({}),
|
||||
});
|
||||
});
|
||||
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
renderWithProviders(<Header />, {
|
||||
auth: {
|
||||
user: {
|
||||
id: 'user-3',
|
||||
plexId: 'plex-3',
|
||||
username: 'reader',
|
||||
role: 'user',
|
||||
},
|
||||
isLoading: false,
|
||||
},
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(errorMock).toHaveBeenCalledWith('Failed to check BookDate config:', expect.any(Error));
|
||||
});
|
||||
|
||||
expect(screen.queryByRole('link', { name: 'BookDate' })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* Component: Interactive Torrent Search Modal Tests
|
||||
* Documentation: documentation/frontend/components.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import React from 'react';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const searchByRequestMock = vi.hoisted(() => vi.fn());
|
||||
const selectTorrentMock = vi.hoisted(() => vi.fn());
|
||||
const searchByAudiobookMock = vi.hoisted(() => vi.fn());
|
||||
const requestWithTorrentMock = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('@/lib/hooks/useRequests', () => ({
|
||||
useInteractiveSearch: () => ({
|
||||
searchTorrents: searchByRequestMock,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
}),
|
||||
useSelectTorrent: () => ({
|
||||
selectTorrent: selectTorrentMock,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
}),
|
||||
useSearchTorrents: () => ({
|
||||
searchTorrents: searchByAudiobookMock,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
}),
|
||||
useRequestWithTorrent: () => ({
|
||||
requestWithTorrent: requestWithTorrentMock,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
}),
|
||||
}));
|
||||
|
||||
const baseResult = {
|
||||
guid: 'torrent-1',
|
||||
rank: 1,
|
||||
title: 'Test Torrent',
|
||||
size: 2.4 * 1024 ** 3,
|
||||
score: 88,
|
||||
bonusPoints: 5,
|
||||
seeders: 42,
|
||||
indexer: 'ProIndexer',
|
||||
format: 'M4B',
|
||||
infoUrl: 'https://example.com/torrent',
|
||||
};
|
||||
|
||||
describe('InteractiveTorrentSearchModal', () => {
|
||||
it('searches by request id on open and confirms download', async () => {
|
||||
searchByRequestMock.mockResolvedValueOnce([baseResult]);
|
||||
selectTorrentMock.mockResolvedValueOnce(undefined);
|
||||
const onClose = vi.fn();
|
||||
const onSuccess = vi.fn();
|
||||
const { InteractiveTorrentSearchModal } = await import('@/components/requests/InteractiveTorrentSearchModal');
|
||||
|
||||
render(
|
||||
<InteractiveTorrentSearchModal
|
||||
isOpen={true}
|
||||
onClose={onClose}
|
||||
onSuccess={onSuccess}
|
||||
requestId="req-123"
|
||||
audiobook={{ title: 'Test Book', author: 'Test Author' }}
|
||||
/>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(searchByRequestMock).toHaveBeenCalledWith('req-123', undefined);
|
||||
});
|
||||
|
||||
expect(await screen.findByText('Test Torrent')).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Download' }));
|
||||
const downloadButtons = screen.getAllByRole('button', { name: 'Download' });
|
||||
fireEvent.click(downloadButtons[downloadButtons.length - 1]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(selectTorrentMock).toHaveBeenCalledWith('req-123', baseResult);
|
||||
});
|
||||
expect(onSuccess).toHaveBeenCalled();
|
||||
expect(onClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('searches by audiobook data and requests with torrent', async () => {
|
||||
searchByAudiobookMock.mockResolvedValueOnce([baseResult]);
|
||||
requestWithTorrentMock.mockResolvedValueOnce(undefined);
|
||||
const onClose = vi.fn();
|
||||
const fullAudiobook = { asin: 'ASIN-1', title: 'Test Book', author: 'Test Author' };
|
||||
const { InteractiveTorrentSearchModal } = await import('@/components/requests/InteractiveTorrentSearchModal');
|
||||
|
||||
render(
|
||||
<InteractiveTorrentSearchModal
|
||||
isOpen={true}
|
||||
onClose={onClose}
|
||||
audiobook={{ title: 'Test Book', author: 'Test Author' }}
|
||||
fullAudiobook={fullAudiobook as any}
|
||||
/>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(searchByAudiobookMock).toHaveBeenCalledWith('Test Book', 'Test Author', 'ASIN-1');
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Download' }));
|
||||
const downloadButtons = screen.getAllByRole('button', { name: 'Download' });
|
||||
fireEvent.click(downloadButtons[downloadButtons.length - 1]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(requestWithTorrentMock).toHaveBeenCalledWith(fullAudiobook, baseResult);
|
||||
});
|
||||
expect(onClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uses a custom title when pressing Enter', async () => {
|
||||
searchByRequestMock.mockResolvedValueOnce([]);
|
||||
searchByRequestMock.mockResolvedValueOnce([]);
|
||||
const { InteractiveTorrentSearchModal } = await import('@/components/requests/InteractiveTorrentSearchModal');
|
||||
|
||||
render(
|
||||
<InteractiveTorrentSearchModal
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
requestId="req-456"
|
||||
audiobook={{ title: 'Original Title', author: 'Author' }}
|
||||
/>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(searchByRequestMock).toHaveBeenCalledWith('req-456', undefined);
|
||||
});
|
||||
|
||||
const input = screen.getByPlaceholderText('Enter book title to search...');
|
||||
fireEvent.change(input, { target: { value: 'Custom Title' } });
|
||||
fireEvent.keyPress(input, { key: 'Enter', code: 'Enter', charCode: 13 });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(searchByRequestMock).toHaveBeenNthCalledWith(2, 'req-456', 'Custom Title');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,187 @@
|
||||
/**
|
||||
* Component: Request Card Tests
|
||||
* Documentation: documentation/frontend/components.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import React from 'react';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const cancelRequestMock = vi.hoisted(() => vi.fn());
|
||||
const manualSearchMock = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('@/lib/hooks/useRequests', () => ({
|
||||
useCancelRequest: () => ({ cancelRequest: cancelRequestMock, isLoading: false }),
|
||||
useManualSearch: () => ({ triggerManualSearch: manualSearchMock, isLoading: false }),
|
||||
}));
|
||||
|
||||
vi.mock('@/components/requests/InteractiveTorrentSearchModal', () => ({
|
||||
InteractiveTorrentSearchModal: ({
|
||||
isOpen,
|
||||
requestId,
|
||||
}: {
|
||||
isOpen: boolean;
|
||||
requestId?: string;
|
||||
}) => (
|
||||
<div data-testid="interactive-modal" data-open={String(isOpen)} data-request-id={requestId} />
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock('next/image', () => ({
|
||||
__esModule: true,
|
||||
default: (props: any) => <img {...props} />,
|
||||
}));
|
||||
|
||||
const baseRequest = {
|
||||
id: 'req-1',
|
||||
status: 'pending',
|
||||
progress: 0,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
audiobook: {
|
||||
id: 'book-1',
|
||||
title: 'Test Book',
|
||||
author: 'Test Author',
|
||||
},
|
||||
};
|
||||
|
||||
describe('RequestCard', () => {
|
||||
beforeEach(() => {
|
||||
cancelRequestMock.mockReset();
|
||||
manualSearchMock.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('shows progress and active indicator for downloads', async () => {
|
||||
const { RequestCard } = await import('@/components/requests/RequestCard');
|
||||
|
||||
render(
|
||||
<RequestCard
|
||||
request={{
|
||||
...baseRequest,
|
||||
status: 'downloading',
|
||||
progress: 45,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Downloading')).toBeInTheDocument();
|
||||
expect(screen.getByText('Active')).toBeInTheDocument();
|
||||
expect(screen.getByText('45%')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('toggles the error message for failed requests', async () => {
|
||||
const { RequestCard } = await import('@/components/requests/RequestCard');
|
||||
|
||||
render(
|
||||
<RequestCard
|
||||
request={{
|
||||
...baseRequest,
|
||||
status: 'failed',
|
||||
errorMessage: 'Failure details',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Show error' }));
|
||||
expect(await screen.findByText('Failure details')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('triggers manual search, interactive search, and cancel actions', async () => {
|
||||
const { RequestCard } = await import('@/components/requests/RequestCard');
|
||||
|
||||
manualSearchMock.mockResolvedValueOnce(undefined);
|
||||
cancelRequestMock.mockResolvedValueOnce(undefined);
|
||||
vi.spyOn(window, 'confirm').mockReturnValue(true);
|
||||
|
||||
render(<RequestCard request={baseRequest} />);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Manual Search' }));
|
||||
await waitFor(() => {
|
||||
expect(manualSearchMock).toHaveBeenCalledWith('req-1');
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Interactive Search' }));
|
||||
expect(screen.getByTestId('interactive-modal')).toHaveAttribute('data-open', 'true');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
await waitFor(() => {
|
||||
expect(cancelRequestMock).toHaveBeenCalledWith('req-1');
|
||||
});
|
||||
});
|
||||
|
||||
it('shows setup indicator when progress is zero', async () => {
|
||||
const { RequestCard } = await import('@/components/requests/RequestCard');
|
||||
|
||||
render(
|
||||
<RequestCard
|
||||
request={{
|
||||
...baseRequest,
|
||||
status: 'processing',
|
||||
progress: 0,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Setting up...')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides action buttons when showActions is false', async () => {
|
||||
const { RequestCard } = await import('@/components/requests/RequestCard');
|
||||
|
||||
render(<RequestCard request={baseRequest} showActions={false} />);
|
||||
|
||||
expect(screen.queryByRole('button', { name: 'Manual Search' })).toBeNull();
|
||||
expect(screen.queryByRole('button', { name: 'Cancel' })).toBeNull();
|
||||
});
|
||||
|
||||
it('alerts when manual search fails', async () => {
|
||||
const { RequestCard } = await import('@/components/requests/RequestCard');
|
||||
|
||||
manualSearchMock.mockRejectedValueOnce(new Error('Search failed'));
|
||||
const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {});
|
||||
|
||||
render(<RequestCard request={baseRequest} />);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Manual Search' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(alertSpy).toHaveBeenCalledWith('Search failed');
|
||||
});
|
||||
});
|
||||
|
||||
it('does not cancel when confirmation is declined', async () => {
|
||||
const { RequestCard } = await import('@/components/requests/RequestCard');
|
||||
|
||||
vi.spyOn(window, 'confirm').mockReturnValue(false);
|
||||
|
||||
render(<RequestCard request={baseRequest} />);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(cancelRequestMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows completed timestamp when available', async () => {
|
||||
const { RequestCard } = await import('@/components/requests/RequestCard');
|
||||
|
||||
render(
|
||||
<RequestCard
|
||||
request={{
|
||||
...baseRequest,
|
||||
completedAt: new Date('2024-01-01T00:00:00Z').toISOString(),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText(/Completed/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Component: Status Badge Tests
|
||||
* Documentation: documentation/frontend/components.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import React from 'react';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { StatusBadge } from '@/components/requests/StatusBadge';
|
||||
|
||||
describe('StatusBadge', () => {
|
||||
it('uses the initializing label for zero-progress downloads', () => {
|
||||
render(<StatusBadge status="downloading" progress={0} />);
|
||||
expect(screen.getByText('Initializing...')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('falls back to the raw status when unknown', () => {
|
||||
render(<StatusBadge status="custom_status" />);
|
||||
expect(screen.getByText('custom_status')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Component: Card Size Controls Tests
|
||||
* Documentation: documentation/frontend/components.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import React from 'react';
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
describe('CardSizeControls', () => {
|
||||
beforeEach(() => {
|
||||
window.innerWidth = 1300;
|
||||
});
|
||||
|
||||
it('moves to the next visible size when zooming in or out', async () => {
|
||||
const onSizeChange = vi.fn();
|
||||
const { CardSizeControls } = await import('@/components/ui/CardSizeControls');
|
||||
|
||||
render(<CardSizeControls size={5} onSizeChange={onSizeChange} />);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Zoom in' }));
|
||||
expect(onSizeChange).toHaveBeenCalledWith(6);
|
||||
|
||||
onSizeChange.mockClear();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Zoom out' }));
|
||||
expect(onSizeChange).toHaveBeenCalledWith(4);
|
||||
});
|
||||
|
||||
it('disables zoom controls at the size boundaries', async () => {
|
||||
const onSizeChange = vi.fn();
|
||||
const { CardSizeControls } = await import('@/components/ui/CardSizeControls');
|
||||
|
||||
const { rerender } = render(<CardSizeControls size={1} onSizeChange={onSizeChange} />);
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Zoom out' })).toBeDisabled();
|
||||
|
||||
rerender(<CardSizeControls size={9} onSizeChange={onSizeChange} />);
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Zoom in' })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* Component: Change Password Modal Tests
|
||||
* Documentation: documentation/frontend/components.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { ChangePasswordModal } from '@/components/ui/ChangePasswordModal';
|
||||
|
||||
describe('ChangePasswordModal', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.useRealTimers();
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
it('shows validation errors when required fields are missing', () => {
|
||||
render(<ChangePasswordModal isOpen onClose={vi.fn()} />);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Change Password' }));
|
||||
|
||||
expect(screen.getByText('Current password is required')).toBeInTheDocument();
|
||||
expect(screen.getByText('New password is required')).toBeInTheDocument();
|
||||
expect(screen.getByText('Please confirm your new password')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('rejects submission when access token is missing', async () => {
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
render(<ChangePasswordModal isOpen onClose={vi.fn()} />);
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Current Password'), {
|
||||
target: { value: 'old-password' },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText('New Password'), {
|
||||
target: { value: 'new-password' },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText('Confirm New Password'), {
|
||||
target: { value: 'new-password' },
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Change Password' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Not authenticated')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('submits successfully and auto-closes after showing success', async () => {
|
||||
vi.useFakeTimers();
|
||||
const onClose = vi.fn();
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ success: true }),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
localStorage.setItem('accessToken', 'token');
|
||||
|
||||
render(<ChangePasswordModal isOpen onClose={onClose} />);
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Current Password'), {
|
||||
target: { value: 'old-password' },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText('New Password'), {
|
||||
target: { value: 'new-password' },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText('Confirm New Password'), {
|
||||
target: { value: 'new-password' },
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Change Password' }));
|
||||
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/api/auth/change-password',
|
||||
expect.objectContaining({ method: 'POST' })
|
||||
);
|
||||
|
||||
expect(screen.getByText('Password changed successfully!')).toBeInTheDocument();
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(2000);
|
||||
});
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('shows server error responses', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
json: async () => ({ error: 'Invalid password' }),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
localStorage.setItem('accessToken', 'token');
|
||||
|
||||
render(<ChangePasswordModal isOpen onClose={vi.fn()} />);
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Current Password'), {
|
||||
target: { value: 'old-password' },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText('New Password'), {
|
||||
target: { value: 'new-password' },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText('Confirm New Password'), {
|
||||
target: { value: 'new-password' },
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Change Password' }));
|
||||
|
||||
expect(await screen.findByText('Invalid password')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Component: Modal Component Tests
|
||||
* Documentation: documentation/frontend/components.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { Modal } from '@/components/ui/Modal';
|
||||
|
||||
describe('Modal', () => {
|
||||
it('locks body scroll while open and closes on escape', () => {
|
||||
const onClose = vi.fn();
|
||||
|
||||
const { unmount } = render(
|
||||
<Modal isOpen onClose={onClose} title="Test Modal">
|
||||
<div>Modal Content</div>
|
||||
</Modal>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Modal Content')).toBeInTheDocument();
|
||||
expect(document.body.style.overflow).toBe('hidden');
|
||||
|
||||
fireEvent.keyDown(document, { key: 'Escape' });
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
|
||||
unmount();
|
||||
expect(document.body.style.overflow).toBe('unset');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Component: Pagination Tests
|
||||
* Documentation: documentation/frontend/components.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import React from 'react';
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { Pagination } from '@/components/ui/Pagination';
|
||||
|
||||
describe('Pagination', () => {
|
||||
it('renders nothing when there is only one page', () => {
|
||||
const { container } = render(<Pagination currentPage={1} totalPages={1} onPageChange={vi.fn()} />);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('renders ellipses for large page ranges', () => {
|
||||
render(<Pagination currentPage={5} totalPages={10} onPageChange={vi.fn()} />);
|
||||
const ellipses = screen.getAllByText('...');
|
||||
expect(ellipses.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('calls onPageChange for navigation controls', () => {
|
||||
const onPageChange = vi.fn();
|
||||
render(<Pagination currentPage={2} totalPages={5} onPageChange={onPageChange} />);
|
||||
|
||||
fireEvent.click(screen.getByLabelText('Previous page'));
|
||||
expect(onPageChange).toHaveBeenCalledWith(1);
|
||||
|
||||
fireEvent.click(screen.getByLabelText('Next page'));
|
||||
expect(onPageChange).toHaveBeenCalledWith(3);
|
||||
|
||||
fireEvent.click(screen.getByLabelText('Page 4'));
|
||||
expect(onPageChange).toHaveBeenCalledWith(4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* Component: Sticky Pagination Tests
|
||||
* Documentation: documentation/frontend/components.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import React from 'react';
|
||||
import { act, fireEvent, render, screen } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { StickyPagination } from '@/components/ui/StickyPagination';
|
||||
|
||||
type ObserverEntry = {
|
||||
isIntersecting: boolean;
|
||||
intersectionRatio: number;
|
||||
target: Element;
|
||||
};
|
||||
|
||||
describe('StickyPagination', () => {
|
||||
const observers: { callback: IntersectionObserverCallback }[] = [];
|
||||
|
||||
beforeEach(() => {
|
||||
observers.length = 0;
|
||||
class MockIntersectionObserver {
|
||||
callback: IntersectionObserverCallback;
|
||||
observe = vi.fn();
|
||||
unobserve = vi.fn();
|
||||
disconnect = vi.fn();
|
||||
takeRecords = vi.fn();
|
||||
|
||||
constructor(callback: IntersectionObserverCallback) {
|
||||
this.callback = callback;
|
||||
observers.push(this);
|
||||
}
|
||||
}
|
||||
|
||||
(global as any).IntersectionObserver = MockIntersectionObserver;
|
||||
});
|
||||
|
||||
it('returns null when there is only one page', () => {
|
||||
const sectionRef = { current: document.createElement('div') };
|
||||
const { container } = render(
|
||||
<StickyPagination
|
||||
currentPage={1}
|
||||
totalPages={1}
|
||||
onPageChange={vi.fn()}
|
||||
sectionRef={sectionRef}
|
||||
label="Popular"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('shows and hides based on section and footer visibility', () => {
|
||||
const sectionRef = { current: document.createElement('div') };
|
||||
const footerRef = { current: document.createElement('div') };
|
||||
|
||||
const { container } = render(
|
||||
<StickyPagination
|
||||
currentPage={2}
|
||||
totalPages={5}
|
||||
onPageChange={vi.fn()}
|
||||
sectionRef={sectionRef}
|
||||
footerRef={footerRef}
|
||||
label="Popular"
|
||||
/>
|
||||
);
|
||||
|
||||
const root = container.querySelector('div.fixed') as HTMLElement;
|
||||
expect(root).toHaveClass('opacity-0');
|
||||
|
||||
act(() => {
|
||||
observers[0].callback(
|
||||
[
|
||||
{
|
||||
isIntersecting: true,
|
||||
intersectionRatio: 0.2,
|
||||
target: sectionRef.current as Element,
|
||||
} as ObserverEntry,
|
||||
],
|
||||
observers[0] as unknown as IntersectionObserver
|
||||
);
|
||||
});
|
||||
|
||||
expect(root).toHaveClass('opacity-100');
|
||||
|
||||
act(() => {
|
||||
observers[1].callback(
|
||||
[
|
||||
{
|
||||
isIntersecting: true,
|
||||
intersectionRatio: 0.2,
|
||||
target: footerRef.current as Element,
|
||||
} as ObserverEntry,
|
||||
],
|
||||
observers[1] as unknown as IntersectionObserver
|
||||
);
|
||||
});
|
||||
|
||||
expect(root).toHaveClass('opacity-0');
|
||||
});
|
||||
|
||||
it('handles navigation and jump input updates', () => {
|
||||
const sectionRef = { current: document.createElement('div') };
|
||||
const onPageChange = vi.fn();
|
||||
|
||||
render(
|
||||
<StickyPagination
|
||||
currentPage={2}
|
||||
totalPages={4}
|
||||
onPageChange={onPageChange}
|
||||
sectionRef={sectionRef}
|
||||
label="Popular"
|
||||
/>
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByLabelText('Next page'));
|
||||
expect(onPageChange).toHaveBeenCalledWith(3);
|
||||
|
||||
fireEvent.click(screen.getByLabelText('Previous page'));
|
||||
expect(onPageChange).toHaveBeenCalledWith(1);
|
||||
|
||||
const input = screen.getByLabelText('Current page') as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: '4' } });
|
||||
fireEvent.blur(input);
|
||||
expect(onPageChange).toHaveBeenCalledWith(4);
|
||||
|
||||
fireEvent.change(input, { target: { value: '99' } });
|
||||
fireEvent.blur(input);
|
||||
expect(input.value).toBe('2');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Component: Toast 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 { ToastProvider, useToast } from '@/components/ui/Toast';
|
||||
|
||||
const ToastHarness = () => {
|
||||
const { success, error } = useToast();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<button type="button" onClick={() => success('Saved', 1000)}>
|
||||
Add Success
|
||||
</button>
|
||||
<button type="button" onClick={() => error('Failed', 0)}>
|
||||
Add Error
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
describe('ToastProvider', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('adds and auto-removes toasts after the duration', async () => {
|
||||
render(
|
||||
<ToastProvider>
|
||||
<ToastHarness />
|
||||
</ToastProvider>
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add Success' }));
|
||||
expect(screen.getByText('Saved')).toBeInTheDocument();
|
||||
|
||||
await act(async () => {
|
||||
vi.advanceTimersByTime(1000);
|
||||
});
|
||||
|
||||
expect(screen.queryByText('Saved')).toBeNull();
|
||||
});
|
||||
|
||||
it('removes a toast when the close button is clicked', () => {
|
||||
render(
|
||||
<ToastProvider>
|
||||
<ToastHarness />
|
||||
</ToastProvider>
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add Error' }));
|
||||
expect(screen.getByText('Failed')).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Close' }));
|
||||
expect(screen.queryByText('Failed')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Component: Version Badge Tests
|
||||
* Documentation: documentation/frontend/components.md
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { VersionBadge } from '@/components/ui/VersionBadge';
|
||||
|
||||
const originalCommit = process.env.NEXT_PUBLIC_GIT_COMMIT;
|
||||
|
||||
describe('VersionBadge', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
if (originalCommit === undefined) {
|
||||
delete process.env.NEXT_PUBLIC_GIT_COMMIT;
|
||||
} else {
|
||||
process.env.NEXT_PUBLIC_GIT_COMMIT = originalCommit;
|
||||
}
|
||||
});
|
||||
|
||||
it('renders short version from build-time commit', async () => {
|
||||
process.env.NEXT_PUBLIC_GIT_COMMIT = 'abcdef1234';
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
render(<VersionBadge />);
|
||||
|
||||
expect(await screen.findByText('v.abcdef1')).toBeInTheDocument();
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('falls back to API when build-time commit is unavailable', async () => {
|
||||
process.env.NEXT_PUBLIC_GIT_COMMIT = 'unknown';
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
json: async () => ({ version: 'v.1.2.3' }),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
render(<VersionBadge />);
|
||||
|
||||
expect(await screen.findByText('v.1.2.3')).toBeInTheDocument();
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/version');
|
||||
});
|
||||
|
||||
it('shows dev version when API fetch fails', async () => {
|
||||
process.env.NEXT_PUBLIC_GIT_COMMIT = 'unknown';
|
||||
const fetchMock = vi.fn().mockRejectedValue(new Error('down'));
|
||||
const errorMock = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
render(<VersionBadge />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('v.dev')).toBeInTheDocument();
|
||||
});
|
||||
expect(errorMock).toHaveBeenCalledWith('Failed to fetch version:', expect.any(Error));
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user