Files
ersatztv/web/src/screens/LibrariesScreen.test.tsx
T
timothyandClaude Opus 4.8 6ce448d265 feat(spa): media-source SPA foundation — shared client, helpers, App-owned popstate wrapper (#202 slice S5)
Owns the shared single-files so the S6a (Local) / S6b (Remote) editor slices touch
disjoint files. Editor screens are stubbed (MediaSourceEditorPlaceholder) for S6.

- web/src/api/mediaSources.ts (+test): client module over the new media-source write
  endpoints (local CRUD + move/path-exists; Plex pin-flow/sign-out; shared remote
  state/connection/libraries/path-replacements/refresh; family = only URL variance),
  DTOs re-exported from generated v1, messageFromMediaSourcesError; barrel export.
- web/src/mediaSources/{familyMeta,paths,pinFlowPoll}.ts (+tests): family labels/routes/
  remote-path column naming (owns RemoteFamily); client-side NormalizePath mirror for
  in-draft dup detection; pure §C1 pin-flow poll state machine (waiting/finalizing/
  success/timeout/budget-exhausted), timer-free and fully unit-tested.
- routing.ts parseLibrariesSubRoute + LibrariesSubRoute union split Local vs Remote.
- App.tsx: libraries route allowSubPaths; LibrariesRouteScreen wrapper dispatching a
  flat switch to placeholders; App-owned popstate (finding 4) — App is the single
  popstate owner, consults canLeaveCurrentScreen() and only on approval updates
  librariesSubPath passed DOWN to the wrapper (wrapper never self-listens); state write
  scoped to the libraries route so Playouts/Media pops stay byte-identical (nit 3).
- LibrariesScreen hub wiring: Add-Source menu (Local/Plex/Jellyfin/Emby), remote source
  gear -> family screen, local library row gear -> edit route; removed the disabled
  Scan-All button + the deferred-sources card (§C7/§D.1).
- Tests: App-owned-popstate dirty-guard case (confirm false keeps URL+sub-screen; true
  navigates); mediaSources client URL/verb mapping; pinFlowPoll transitions; familyMeta/
  paths units; hub-wiring navigation.
- docs/spa-conventions.md §8 (resolved sub-path+dirty-guard caveat -> App-owned popstate)
  + §2 exemplar list (guarded-route exception).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 16:11:16 +02:00

446 lines
17 KiB
TypeScript

import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { LibrariesScreen } from './LibrariesScreen';
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status });
}
// MediaSourceLibraryResponseModel row.
function library(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
id: 31,
itemCount: 0,
lastScan: null,
mediaKind: 'Movies',
name: 'Movies',
...overrides
};
}
// MediaSourceResponseModel row.
function mediaSource(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
connectionAddress: null,
id: 30,
kind: 'Local',
libraries: [],
name: 'Local',
...overrides
};
}
interface MockOptions {
mediaSources?: unknown[];
mediaSourcesFailuresBeforeSuccess?: number;
libraryScanStatuses?: unknown[];
libraryScanStatusSequence?: unknown[][] | null;
mutationFailures?: Record<string, { detail?: string; status?: number; title?: string }>;
}
interface MockHandle {
fetchSpy: ReturnType<typeof vi.spyOn>;
requests: Array<{ url: string; method: string; body: unknown }>;
}
function mockApi(options: MockOptions = {}): MockHandle {
const requests: Array<{ url: string; method: string; body: unknown }> = [];
const mediaSources = options.mediaSources ?? [mediaSource()];
const mutationFailures = options.mutationFailures ?? {};
let remainingMediaSourcesFailures = options.mediaSourcesFailuresBeforeSuccess ?? 0;
let scanStatusSequenceIndex = 0;
const fetchSpy = 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;
requests.push({ url, method, body });
if (url === '/api/media-sources' && method === 'GET') {
if (remainingMediaSourcesFailures > 0) {
remainingMediaSourcesFailures -= 1;
return Promise.resolve(new Response(null, { status: 500 }));
}
return Promise.resolve(jsonResponse(mediaSources));
}
if (url === '/api/libraries/scan-status' && method === 'GET') {
if (options.libraryScanStatusSequence) {
const sequenceValue =
options.libraryScanStatusSequence[Math.min(scanStatusSequenceIndex, options.libraryScanStatusSequence.length - 1)];
scanStatusSequenceIndex += 1;
return Promise.resolve(jsonResponse(sequenceValue));
}
return Promise.resolve(jsonResponse(options.libraryScanStatuses ?? []));
}
if (/^\/api\/libraries\/\d+\/scan$/.test(url) && method === 'POST') {
if (url in mutationFailures) {
return Promise.resolve(jsonResponse(mutationFailures[url], mutationFailures[url].status ?? 422));
}
return Promise.resolve(new Response(null, { status: 202 }));
}
return Promise.resolve(jsonResponse(null, 404));
});
return { fetchSpy, requests };
}
function fetchCount(handle: MockHandle, path: string): number {
return handle.requests.filter((r) => r.url === path).length;
}
async function runPollTick(intervalHandlers: Array<() => void>): Promise<void> {
await act(async () => {
intervalHandlers.forEach((handler) => handler());
});
}
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
beforeEach(() => {
vi.restoreAllMocks();
});
describe('LibrariesScreen', () => {
it('renders sources and libraries from live media source and scan status APIs', async () => {
const handle = mockApi({
libraryScanStatuses: [{ libraryId: 31, percent: 0.625 }],
mediaSources: [
mediaSource({
connectionAddress: null,
id: 30,
kind: 'Local',
libraries: [
library({ id: 31, itemCount: 1250, lastScan: '2026-07-05T14:30:00Z', mediaKind: 'Movies', name: 'Movies' }),
library({ id: 32, itemCount: 14, lastScan: null, mediaKind: 'OtherVideos', name: 'Station IDs' })
],
name: 'Local'
}),
mediaSource({
connectionAddress: 'https://plex.example.test',
id: 40,
kind: 'Plex',
libraries: [
library({ id: 41, itemCount: 80, lastScan: '2026-07-04T08:00:00Z', mediaKind: 'Shows', name: 'TV Shows' })
],
name: 'Plex Server'
}),
mediaSource({
connectionAddress: 'https://jellyfin.example.test',
id: 50,
kind: 'Jellyfin',
libraries: [],
name: 'Jellyfin Home'
}),
mediaSource({
connectionAddress: 'https://emby.example.test',
id: 60,
kind: 'Emby',
libraries: [
library({ id: 61, itemCount: 22, lastScan: '2026-07-01T00:00:00Z', mediaKind: 'MusicVideos', name: 'Music Videos' })
],
name: 'Emby Archive'
})
]
});
render(<LibrariesScreen />);
expect(await screen.findByRole('heading', { name: 'Media Libraries' })).toBeInTheDocument();
expect(screen.getByText('4 sources')).toBeInTheDocument();
expect(screen.getByText('1,366 items')).toBeInTheDocument();
expect(screen.getByRole('region', { name: 'Local media source' })).toBeInTheDocument();
expect(screen.getByText('Local connection')).toBeInTheDocument();
expect(screen.getByRole('region', { name: 'Plex Server media source' })).toBeInTheDocument();
expect(screen.getByText('https://plex.example.test')).toBeInTheDocument();
expect(screen.getAllByText('Movies').length).toBeGreaterThan(0);
expect(screen.getByText('Station IDs')).toBeInTheDocument();
expect(screen.getByText('TV Shows')).toBeInTheDocument();
expect(screen.getAllByText('Music Videos').length).toBeGreaterThan(0);
expect(screen.getByText('Other Videos')).toBeInTheDocument();
// "Scanning" appears twice: once as the source-header status label (paired with the
// StatusDot, not color alone) and once as the per-library scanning Badge.
expect(screen.getAllByText('Scanning').length).toBeGreaterThan(0);
// Wire contract: percent is a 0-1 fraction (0.625) - the UI must render it as 63%, not 0.625%.
expect(screen.getByText('63%')).toBeInTheDocument();
expect(screen.getAllByText('Synced').length).toBeGreaterThan(0);
expect(screen.getAllByText('Never scanned').length).toBeGreaterThan(0);
// Add Source is now a live menu trigger; the disabled Scan All button and the deferred-card were
// removed in slice S5 (design §C7/§D.1).
expect(screen.getByRole('button', { name: 'Add Source' })).toBeEnabled();
expect(screen.queryByRole('button', { name: 'Scan All' })).not.toBeInTheDocument();
expect(screen.queryByText('Adding sources is deferred to the existing server setup screens.')).not.toBeInTheDocument();
expect(handle.fetchSpy).toHaveBeenCalledWith('/api/media-sources', expect.any(Object));
expect(handle.fetchSpy).toHaveBeenCalledWith('/api/libraries/scan-status', expect.any(Object));
});
it('converts 0 and 1 fractional scan-status percents to 0% and 100%', async () => {
mockApi({
libraryScanStatuses: [
{ libraryId: 31, percent: 0 },
{ libraryId: 32, percent: 1 }
],
mediaSources: [
mediaSource({
libraries: [
library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' }),
library({ id: 32, itemCount: 5, mediaKind: 'Shows', name: 'TV Shows' })
]
})
]
});
render(<LibrariesScreen />);
expect(await screen.findByText('0%')).toBeInTheDocument();
expect(screen.getByText('100%')).toBeInTheDocument();
});
it('triggers a library scan via POST /api/libraries/{id}/scan, disables the button while in flight, and polls scan status', async () => {
const handle = mockApi({
libraryScanStatuses: [],
libraryScanStatusSequence: [[], [{ libraryId: 31, percent: 0.05 }]],
mediaSources: [
mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] })
]
});
render(<LibrariesScreen />);
expect((await screen.findAllByText('Movies')).length).toBeGreaterThan(0);
fireEvent.click(screen.getByRole('button', { name: 'Scan Movies' }));
await waitFor(() => {
expect(handle.fetchSpy).toHaveBeenCalledWith('/api/libraries/31/scan', expect.objectContaining({ method: 'POST' }));
});
expect(await screen.findByText('5%')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Scan Movies' })).toBeDisabled();
});
it('stops scan polling and refreshes sources once when scans complete', async () => {
const intervalHandlers: Array<() => void> = [];
vi.spyOn(window, 'setInterval').mockImplementation((handler: TimerHandler, timeout?: number) => {
if (typeof handler === 'function' && (timeout ?? 0) >= 10000) {
intervalHandlers.push(handler as () => void);
}
return intervalHandlers.length;
});
vi.spyOn(window, 'clearInterval').mockImplementation(() => undefined);
const handle = mockApi({
libraryScanStatusSequence: [
[{ libraryId: 31, percent: 0.75 }],
[]
],
mediaSources: [
mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] })
]
});
render(<LibrariesScreen />);
expect(await screen.findByText('75%')).toBeInTheDocument();
const sourceFetchesBeforeCompletion = fetchCount(handle, '/api/media-sources');
await runPollTick(intervalHandlers);
expect(screen.queryByText('75%')).not.toBeInTheDocument();
expect(fetchCount(handle, '/api/media-sources')).toBe(sourceFetchesBeforeCompletion + 1);
});
it('reconciles a 409 "already scanning" against scan-status without an error toast (#232)', async () => {
mockApi({
libraryScanStatusSequence: [
[], // initial screen load: nothing active yet
[{ libraryId: 31, percent: 0.3 }] // post-409 reconcile fetch: the in-progress scan
],
mediaSources: [
mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] })
],
mutationFailures: {
'/api/libraries/31/scan': { status: 409 }
}
});
render(<LibrariesScreen />);
expect((await screen.findAllByText('Movies')).length).toBeGreaterThan(0);
fireEvent.click(screen.getByRole('button', { name: 'Scan Movies' }));
expect(await screen.findByText('30%')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Scan Movies' })).toBeDisabled();
expect(screen.queryByText(/Request failed/)).not.toBeInTheDocument();
expect(screen.queryByText(/Unable to scan/)).not.toBeInTheDocument();
});
it('surfaces a 422 "sync disabled" scan rejection and leaves the button enabled (#232)', async () => {
mockApi({
libraryScanStatuses: [],
mediaSources: [
mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] })
],
mutationFailures: {
'/api/libraries/31/scan': { detail: 'Item sync is disabled for library 31.', status: 422 }
}
});
render(<LibrariesScreen />);
expect((await screen.findAllByText('Movies')).length).toBeGreaterThan(0);
fireEvent.click(screen.getByRole('button', { name: 'Scan Movies' }));
expect(await screen.findByText('Item sync is disabled for library 31.')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Scan Movies' })).not.toBeDisabled();
});
it('shows Libraries API errors and retries', async () => {
// 1 failure (the initial mount's load) then success on the Retry-triggered reload - unlike
// the App-level nav-smoke test, this standalone render has no earlier Dashboard fetch
// consuming a failure first.
mockApi({
mediaSourcesFailuresBeforeSuccess: 1,
mediaSources: [mediaSource({ libraries: [] })]
});
render(<LibrariesScreen />);
expect(await screen.findByText('Request failed with status 500')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
expect(await screen.findByRole('heading', { name: 'Media Libraries' })).toBeInTheDocument();
});
it('shows scan trigger failures without inventing application ProblemDetails', async () => {
mockApi({
mediaSources: [
mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] })
],
mutationFailures: {
'/api/libraries/31/scan': { status: 404 }
}
});
render(<LibrariesScreen />);
expect((await screen.findAllByText('Movies')).length).toBeGreaterThan(0);
fireEvent.click(screen.getByRole('button', { name: 'Scan Movies' }));
expect(await screen.findByText('Request failed with status 404')).toBeInTheDocument();
});
it('scans every library in a source when its Scan-all button is clicked', async () => {
const handle = mockApi({
mediaSources: [
mediaSource({
id: 30,
libraries: [
library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' }),
library({ id: 32, itemCount: 5, mediaKind: 'Shows', name: 'TV Shows' })
],
name: 'Local'
})
]
});
render(<LibrariesScreen />);
expect(await screen.findByText('TV Shows')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Scan all libraries in Local' }));
await waitFor(() => {
expect(handle.fetchSpy).toHaveBeenCalledWith('/api/libraries/31/scan', expect.objectContaining({ method: 'POST' }));
});
await waitFor(() => {
expect(handle.fetchSpy).toHaveBeenCalledWith('/api/libraries/32/scan', expect.objectContaining({ method: 'POST' }));
});
expect(fetchCount(handle, '/api/libraries/31/scan')).toBe(1);
expect(fetchCount(handle, '/api/libraries/32/scan')).toBe(1);
});
it('shows an empty state when no media sources exist', async () => {
mockApi({ mediaSources: [] });
render(<LibrariesScreen />);
expect(await screen.findByText('No media sources returned')).toBeInTheDocument();
});
describe('hub wiring (slice S5)', () => {
it('Add Source menu navigates to the local-new and each family route', async () => {
const pushSpy = vi.spyOn(window.history, 'pushState');
mockApi({ mediaSources: [mediaSource({ libraries: [] })] });
render(<LibrariesScreen />);
await screen.findByRole('heading', { name: 'Media Libraries' });
// Local library → create editor route.
fireEvent.click(screen.getByRole('button', { name: 'Add Source' }));
fireEvent.click(screen.getByRole('menuitem', { name: 'Local library' }));
expect(pushSpy).toHaveBeenLastCalledWith(null, '', '/app/libraries/local/new');
// Plex → its family screen.
fireEvent.click(screen.getByRole('button', { name: 'Add Source' }));
fireEvent.click(screen.getByRole('menuitem', { name: 'Plex' }));
expect(pushSpy).toHaveBeenLastCalledWith(null, '', '/app/libraries/plex');
// Jellyfin → its family screen.
fireEvent.click(screen.getByRole('button', { name: 'Add Source' }));
fireEvent.click(screen.getByRole('menuitem', { name: 'Jellyfin' }));
expect(pushSpy).toHaveBeenLastCalledWith(null, '', '/app/libraries/jellyfin');
// Emby → its family screen.
fireEvent.click(screen.getByRole('button', { name: 'Add Source' }));
fireEvent.click(screen.getByRole('menuitem', { name: 'Emby' }));
expect(pushSpy).toHaveBeenLastCalledWith(null, '', '/app/libraries/emby');
});
it('a remote source gear navigates to its family screen', async () => {
const pushSpy = vi.spyOn(window.history, 'pushState');
mockApi({
mediaSources: [
mediaSource({
connectionAddress: 'https://plex.example.test',
id: 40,
kind: 'Plex',
libraries: [library({ id: 41, mediaKind: 'Shows', name: 'TV Shows' })],
name: 'Plex Server'
})
]
});
render(<LibrariesScreen />);
await screen.findByText('TV Shows');
fireEvent.click(screen.getByRole('button', { name: 'Manage Plex Server' }));
expect(pushSpy).toHaveBeenLastCalledWith(null, '', '/app/libraries/plex');
});
it('a local library row gear navigates to that library edit route; local sources have no source-level gear', async () => {
const pushSpy = vi.spyOn(window.history, 'pushState');
mockApi({
mediaSources: [
mediaSource({
id: 30,
kind: 'Local',
libraries: [library({ id: 31, mediaKind: 'Movies', name: 'Movies' })],
name: 'Local'
})
]
});
render(<LibrariesScreen />);
expect((await screen.findAllByText('Movies')).length).toBeGreaterThan(0);
// No source-level "Manage" gear for a Local source.
expect(screen.queryByRole('button', { name: 'Manage Local' })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Edit Movies' }));
expect(pushSpy).toHaveBeenLastCalledWith(null, '', '/app/libraries/local/31');
});
});
});