Files
ersatztv/web/src/screens/CollectionsScreen.test.tsx
T
timothy 72b6d0a76a
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 4m33s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 4m46s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
fix(web): scope library/add-item pickers to their 4 media kinds (#168 review)
GET /api/library/browse without mediaType now spans all 10 media kinds
(was 4: Movie/TelevisionShow/TelevisionSeason/Artist), which flooded two
pickers with episodes/songs/etc. mixed in with the intended top-level
items. Fan both consumers out per-kind and merge, restoring pre-#168
scoping without touching the API:

- ChannelBuilder's library browse tab now fans out Movie/TelevisionShow/
  TelevisionSeason/Artist per page (mirrors the existing loadCollections
  pattern) and sums per-kind totalCount so paging/load-more still works.
- CollectionsScreen's add-items search now fans out over the same 4
  addable kinds instead of filtering one unscoped page client-side.

Extended App.test.tsx and CollectionsScreen.test.tsx to assert the
per-kind requests and updated a few fixtures that relied on the old
unscoped browse call returning collection-kind items under the library
tab.
2026-07-07 16:06:50 +02:00

326 lines
12 KiB
TypeScript

import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { CollectionsScreen } from './CollectionsScreen';
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
headers: { 'Content-Type': 'application/json' },
status
});
}
const manualCollections = [
{ collectionType: 'Collection', id: 1, name: 'Favorites', state: 'Normal', useCustomPlaybackOrder: false },
{ collectionType: 'Collection', id: 2, name: 'Kids', state: 'Normal', useCustomPlaybackOrder: true }
];
const smartCollections = [{ id: 10, name: 'Action', query: 'genre:action' }];
interface MockOptions {
manual?: unknown[];
smart?: unknown[];
onRequest?: (url: string, method: string, body: unknown) => Response | null;
}
function mockApi(options: MockOptions = {}) {
const manual = options.manual ?? manualCollections;
const smart = options.smart ?? smartCollections;
return vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
const url = input.toString();
const method = (init?.method ?? 'GET').toUpperCase();
const body = init?.body ? JSON.parse(String(init.body)) : undefined;
if (options.onRequest) {
const override = options.onRequest(url, method, body);
if (override) {
return Promise.resolve(override);
}
}
if (url === '/api/collections' && method === 'GET') {
return Promise.resolve(jsonResponse(manual));
}
if (url === '/api/smart-collections' && method === 'GET') {
return Promise.resolve(jsonResponse(smart));
}
if (url.startsWith('/api/library/browse')) {
return Promise.resolve(jsonResponse({ page: [], totalCount: 0 }));
}
return Promise.resolve(new Response(null, { status: 204 }));
});
}
describe('CollectionsScreen', () => {
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
beforeEach(() => {
window.localStorage.clear();
});
it('renders both manual and smart collections', async () => {
mockApi();
render(<CollectionsScreen />);
expect(await screen.findByText('Favorites')).toBeInTheDocument();
expect(screen.getByText('Kids')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /Smart/ }));
expect(await screen.findByText('Action')).toBeInTheDocument();
expect(screen.getByText('genre:action')).toBeInTheDocument();
});
it('shows an error state when loading fails', async () => {
mockApi({
onRequest: (url) => (url === '/api/collections' ? jsonResponse({ status: 500, title: 'Boom' }, 500) : null)
});
render(<CollectionsScreen />);
expect(await screen.findByText('Boom')).toBeInTheDocument();
});
it('creates a manual collection via POST', async () => {
const fetchMock = mockApi({
onRequest: (url, method) =>
url === '/api/collections' && method === 'POST'
? jsonResponse({ collectionType: 'Collection', id: 3, name: 'New One', state: 'Normal', useCustomPlaybackOrder: false }, 201)
: null
});
render(<CollectionsScreen />);
await screen.findByText('Favorites');
fireEvent.click(screen.getByRole('button', { name: 'New collection' }));
const dialog = screen.getByRole('dialog');
fireEvent.change(within(dialog).getByPlaceholderText('Collection name'), { target: { value: 'New One' } });
fireEvent.click(within(dialog).getByRole('button', { name: 'Create' }));
await waitFor(() => {
expect(
fetchMock.mock.calls.some(
([u, init]) => u === '/api/collections' && (init?.method ?? '').toUpperCase() === 'POST'
)
).toBe(true);
});
const postCall = fetchMock.mock.calls.find(
([u, init]) => u === '/api/collections' && (init?.method ?? '').toUpperCase() === 'POST'
);
expect(JSON.parse(String(postCall?.[1]?.body))).toEqual({ name: 'New One' });
});
it('renames a manual collection via PUT', async () => {
const fetchMock = mockApi({
onRequest: (url, method) =>
url === '/api/collections/1' && method === 'PUT'
? jsonResponse({ collectionType: 'Collection', id: 1, name: 'Renamed', state: 'Normal', useCustomPlaybackOrder: false })
: null
});
render(<CollectionsScreen />);
await screen.findByText('Favorites');
fireEvent.click(screen.getAllByRole('button', { name: 'Rename' })[0]);
const dialog = screen.getByRole('dialog');
const input = within(dialog).getByPlaceholderText('Collection name') as HTMLInputElement;
expect(input.value).toBe('Favorites');
fireEvent.change(input, { target: { value: 'Renamed' } });
fireEvent.click(within(dialog).getByRole('button', { name: 'Save' }));
await waitFor(() => {
const putCall = fetchMock.mock.calls.find(
([u, init]) => u === '/api/collections/1' && (init?.method ?? '').toUpperCase() === 'PUT'
);
expect(putCall).toBeDefined();
expect(JSON.parse(String(putCall?.[1]?.body))).toMatchObject({ name: 'Renamed' });
});
});
it('toggles custom playback order via PUT', async () => {
const fetchMock = mockApi({
onRequest: (url, method) =>
url === '/api/collections/1' && method === 'PUT'
? jsonResponse({ collectionType: 'Collection', id: 1, name: 'Favorites', state: 'Normal', useCustomPlaybackOrder: true })
: null
});
render(<CollectionsScreen />);
await screen.findByText('Favorites');
// First switch in the list belongs to "Favorites".
const switches = screen.getAllByRole('switch');
fireEvent.click(switches[0]);
await waitFor(() => {
const putCall = fetchMock.mock.calls.find(
([u, init]) => u === '/api/collections/1' && (init?.method ?? '').toUpperCase() === 'PUT'
);
expect(putCall).toBeDefined();
expect(JSON.parse(String(putCall?.[1]?.body))).toMatchObject({ useCustomPlaybackOrder: true });
});
});
it('confirms and DELETEs a manual collection', async () => {
const fetchMock = mockApi();
render(<CollectionsScreen />);
await screen.findByText('Favorites');
const rows = screen.getAllByRole('button', { name: 'Delete' });
fireEvent.click(rows[0]);
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByText(/Delete "Favorites"/)).toBeInTheDocument();
fireEvent.click(within(dialog).getByRole('button', { name: 'Delete' }));
await waitFor(() => {
expect(
fetchMock.mock.calls.some(
([u, init]) => u === '/api/collections/1' && (init?.method ?? '').toUpperCase() === 'DELETE'
)
).toBe(true);
});
});
it('creates a smart collection and previews the query against browse', async () => {
const fetchMock = mockApi({
onRequest: (url, method) => {
if (url.startsWith('/api/library/browse')) {
return jsonResponse({ page: [{ id: 1, mediaType: 'Movie', title: 'The Matrix' }], totalCount: 1 });
}
if (url === '/api/smart-collections' && method === 'POST') {
return jsonResponse({ id: 11, name: 'Sci-Fi', query: 'genre:scifi' }, 201);
}
return null;
}
});
render(<CollectionsScreen />);
await screen.findByText('Favorites');
fireEvent.click(screen.getByRole('button', { name: /Smart/ }));
fireEvent.click(screen.getByRole('button', { name: 'New smart collection' }));
const dialog = screen.getByRole('dialog');
fireEvent.change(within(dialog).getByPlaceholderText('Smart collection name'), { target: { value: 'Sci-Fi' } });
fireEvent.change(within(dialog).getByPlaceholderText(/genre/), { target: { value: 'genre:scifi' } });
fireEvent.click(within(dialog).getByRole('button', { name: 'Preview results' }));
expect(await within(dialog).findByText('The Matrix')).toBeInTheDocument();
expect(within(dialog).getByText('1 matches')).toBeInTheDocument();
const browseCall = fetchMock.mock.calls.find(([u]) => u.toString().startsWith('/api/library/browse'));
expect(new URL(String(browseCall?.[0]), 'http://localhost').searchParams.get('query')).toBe('genre:scifi');
fireEvent.click(within(dialog).getByRole('button', { name: 'Create' }));
await waitFor(() => {
const postCall = fetchMock.mock.calls.find(
([u, init]) => u === '/api/smart-collections' && (init?.method ?? '').toUpperCase() === 'POST'
);
expect(postCall).toBeDefined();
expect(JSON.parse(String(postCall?.[1]?.body))).toEqual({ name: 'Sci-Fi', query: 'genre:scifi' });
});
});
it('opens a manual collection and previews its items via a collection: query', async () => {
const fetchMock = mockApi({
onRequest: (url) => {
if (url.startsWith('/api/library/browse')) {
const q = new URL(url, 'http://localhost').searchParams.get('query') ?? '';
if (q.startsWith('collection:')) {
return jsonResponse({ page: [{ id: 5, mediaItemId: 5, mediaType: 'Movie', title: 'Inception' }], totalCount: 1 });
}
}
return null;
}
});
render(<CollectionsScreen />);
await screen.findByText('Favorites');
fireEvent.click(screen.getByText('Favorites'));
expect(await screen.findByText('Inception')).toBeInTheDocument();
expect(screen.getByText(/best-effort search preview/)).toBeInTheDocument();
const browseCall = fetchMock.mock.calls.find(([u]) =>
u.toString().includes('collection%3A')
);
expect(new URL(String(browseCall?.[0]), 'http://localhost').searchParams.get('query')).toBe('collection:"Favorites"');
});
it('fans the add-items search out over the 4 addable kinds and merges the results', async () => {
const byType: Record<string, { id: number; mediaType: string; title: string }> = {
Movie: { id: 1, mediaType: 'Movie', title: 'Zathura' },
TelevisionShow: { id: 2, mediaType: 'TelevisionShow', title: 'Adventure Time' },
TelevisionSeason: { id: 3, mediaType: 'TelevisionSeason', title: 'Melon Season 1' },
Artist: { id: 4, mediaType: 'Artist', title: 'Between Movie and Show' }
};
const fetchMock = mockApi({
onRequest: (url) => {
if (url.startsWith('/api/library/browse')) {
const params = new URL(url, 'http://localhost').searchParams;
const query = params.get('query') ?? '';
// The manual-collection preview query (collection:"Favorites") should not
// reach the add-items search path.
if (query.startsWith('collection:')) {
return jsonResponse({ page: [], totalCount: 0 });
}
const mediaType = params.get('mediaType');
const item = mediaType ? byType[mediaType] : undefined;
return jsonResponse(item ? { page: [item], totalCount: 1 } : { page: [], totalCount: 0 });
}
return null;
}
});
render(<CollectionsScreen />);
await screen.findByText('Favorites');
fireEvent.click(screen.getByText('Favorites'));
await screen.findByText(/best-effort search preview/);
fireEvent.click(screen.getByRole('button', { name: 'Add items' }));
const dialog = screen.getByRole('dialog');
fireEvent.change(within(dialog).getByPlaceholderText('Search movies, shows, seasons, artists…'), {
target: { value: 'a' }
});
fireEvent.click(within(dialog).getByRole('button', { name: 'Search' }));
expect(await within(dialog).findByText('Adventure Time')).toBeInTheDocument();
expect(within(dialog).getByText('Zathura')).toBeInTheDocument();
expect(within(dialog).getByText('Melon Season 1')).toBeInTheDocument();
expect(within(dialog).getByText('Between Movie and Show')).toBeInTheDocument();
const browseTypes = fetchMock.mock.calls
.map(([u]) => u.toString())
.filter((u) => u.startsWith('/api/library/browse'))
.map((u) => new URL(u, 'http://localhost').searchParams.get('mediaType'))
.filter((mediaType): mediaType is string => mediaType != null);
expect(new Set(browseTypes)).toEqual(new Set(['Movie', 'TelevisionShow', 'TelevisionSeason', 'Artist']));
});
});