Files
ersatztv/web/src/App.test.tsx
T
2026-07-02 18:36:56 +02:00

345 lines
12 KiB
TypeScript

import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { App } from './App';
import { Button, Checkbox, Input, ProgressBar, Switch, Tabs, Toast, Tooltip } from './components';
import {
applyDesignSystemTheme,
designSystemStylesheet,
getStoredDesignSystemTheme
} from './designSystem';
describe('ChicoryTV SPA scaffold', () => {
afterEach(() => {
cleanup();
window.history.replaceState(null, '', '/');
});
beforeEach(() => {
window.localStorage.clear();
document.documentElement.removeAttribute('data-theme');
window.history.replaceState(null, '', '/app');
vi.restoreAllMocks();
mockDashboardApi();
});
it('renders the admin shell chrome and loads the design system stylesheet', () => {
render(<App />);
expect(screen.getByRole('img', { name: 'ChicoryTV' })).toBeInTheDocument();
expect(screen.getByRole('navigation', { name: 'Primary' })).toBeInTheDocument();
expect(screen.getByRole('banner')).toBeInTheDocument();
expect(screen.getByRole('searchbox', { name: 'Search' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Connect' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Add Channel' })).toBeInTheDocument();
expect(screen.getByText('Healthy')).toBeInTheDocument();
expect(designSystemStylesheet).toBe('../../design-system/styles.css');
});
it('routes between shell screen slots without a page reload', () => {
render(<App />);
fireEvent.click(screen.getByRole('link', { name: 'Channels' }));
expect(screen.getByRole('heading', { name: 'Channels' })).toBeInTheDocument();
expect(screen.getByText('Channel list workspace')).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Channels' })).toHaveAttribute(
'aria-current',
'page'
);
expect(window.location.pathname).toBe('/app/channels');
fireEvent.click(screen.getByRole('link', { name: 'Schedules' }));
expect(screen.getByRole('heading', { name: 'Schedules' })).toBeInTheDocument();
expect(screen.getByText('Schedule editor workspace')).toBeInTheDocument();
expect(window.location.pathname).toBe('/app/schedules');
});
it('preserves native browser behavior for modified nav link clicks', () => {
render(<App />);
fireEvent.click(screen.getByRole('link', { name: 'Channels' }), { ctrlKey: true });
expect(screen.getByRole('heading', { name: 'Dashboard' })).toBeInTheDocument();
expect(window.location.pathname).toBe('/app');
});
it('selects the active screen from the current location', () => {
window.history.replaceState(null, '', '/app/guide');
render(<App />);
expect(screen.getByRole('heading', { name: 'Guide' })).toBeInTheDocument();
expect(screen.getByText('EPG grid workspace')).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Guide' })).toHaveAttribute('aria-current', 'page');
});
it('shows a not-found screen for unknown app routes', () => {
window.history.replaceState(null, '', '/app/channels/42');
render(<App />);
expect(screen.getByRole('heading', { name: 'Page not found' })).toBeInTheDocument();
expect(screen.getByText('/app/channels/42')).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Dashboard' })).not.toHaveAttribute(
'aria-current',
'page'
);
});
it('opens the Connect menu with absolute player endpoints and live channel count', async () => {
mockDashboardApi({
channels: [
{ id: 1, name: 'Retro Cartoons', number: '5.1' },
{ id: 2, name: 'News 24', number: '24' }
]
});
render(<App />);
fireEvent.click(screen.getByRole('button', { name: 'Connect' }));
expect(screen.getByRole('dialog', { name: 'Connect a player' })).toBeInTheDocument();
expect(screen.getByText('M3U playlist')).toBeInTheDocument();
expect(screen.getByText('XMLTV guide')).toBeInTheDocument();
expect(screen.getByText(`${window.location.origin}/iptv/channels.m3u`)).toBeInTheDocument();
expect(screen.getByText(`${window.location.origin}/iptv/xmltv.xml`)).toBeInTheDocument();
expect(await screen.findByText('2 channels')).toBeInTheDocument();
expect(screen.queryByRole('checkbox', { name: 'Only enabled channels' })).not.toBeInTheDocument();
});
it('focuses the Connect menu and closes it with Escape', () => {
render(<App />);
fireEvent.click(screen.getByRole('button', { name: 'Connect' }));
const dialog = screen.getByRole('dialog', { name: 'Connect a player' });
expect(dialog).toHaveFocus();
fireEvent.keyDown(dialog, { key: 'Escape' });
expect(screen.queryByRole('dialog', { name: 'Connect a player' })).not.toBeInTheDocument();
});
it('applies the warm design-system default by removing the theme attribute', () => {
document.documentElement.dataset.theme = 'cool';
applyDesignSystemTheme('warm');
expect(document.documentElement).not.toHaveAttribute('data-theme');
expect(window.localStorage.getItem('ctv-theme')).toBe('warm');
});
it('applies and persists alternate design-system themes', () => {
applyDesignSystemTheme('cool');
expect(document.documentElement).toHaveAttribute('data-theme', 'cool');
expect(window.localStorage.getItem('ctv-theme')).toBe('cool');
});
it('ignores invalid persisted themes', () => {
window.localStorage.setItem('ctv-theme', 'unknown');
expect(getStoredDesignSystemTheme()).toBe('warm');
});
it('switches themes from the shell controls', () => {
render(<App />);
fireEvent.click(screen.getByRole('button', { name: 'Dual accent theme' }));
expect(document.documentElement).toHaveAttribute('data-theme', 'dual');
expect(window.localStorage.getItem('ctv-theme')).toBe('dual');
expect(screen.getByRole('button', { name: 'Dual accent theme' })).toHaveAttribute(
'aria-pressed',
'true'
);
});
it('renders routed placeholder cards for the downstream screen work', async () => {
render(<App />);
expect(await screen.findByText('On air now')).toBeInTheDocument();
expect(screen.getByText('System health')).toBeInTheDocument();
expect(screen.getByText('Recent activity')).toBeInTheDocument();
expect(screen.getByText('Release notes')).toBeInTheDocument();
});
it('renders dashboard cards and stats from live API responses', async () => {
mockDashboardApi({
channels: [
{
fFmpegProfile: 'HLS Direct',
id: 1,
language: 'en',
name: 'Retro Cartoons',
number: '5.1',
streamingMode: 'HLS Direct'
},
{
fFmpegProfile: 'MPEG-TS',
id: 2,
language: 'fr',
name: 'News 24',
number: '24',
streamingMode: 'MPEG-TS'
}
],
collections: [{ id: 10, name: 'Saturday Morning' }],
schedules: [{ id: 20, name: 'Default Schedule' }],
sessions: [{ channelNumber: '5.1' }, { channelNumber: '24' }],
version: { apiVersion: 3, appVersion: '26.4.0-test' }
});
render(<App />);
expect(await screen.findByRole('heading', { name: 'On air now' })).toBeInTheDocument();
expect(await screen.findByText('Retro Cartoons')).toBeInTheDocument();
expect(screen.getByText('5.1')).toBeInTheDocument();
expect(screen.getByText('News 24')).toBeInTheDocument();
expect(screen.getByText('24')).toBeInTheDocument();
expect(screen.getByText('2 streaming')).toBeInTheDocument();
expect(screen.getAllByText('2')).toHaveLength(2);
expect(screen.getAllByText('1')).toHaveLength(2);
expect(screen.getByText('26.4.0-test')).toBeInTheDocument();
expect(window.fetch).toHaveBeenCalledWith('/api/channels', expect.any(Object));
expect(window.fetch).toHaveBeenCalledWith('/api/sessions', expect.any(Object));
expect(window.fetch).toHaveBeenCalledWith('/api/version', expect.any(Object));
});
it('shows the dashboard loading state while requests are pending', async () => {
vi.spyOn(window, 'fetch').mockImplementation(() => new Promise<Response>(() => {}));
render(<App />);
expect(await screen.findByText('Loading dashboard')).toBeInTheDocument();
});
it('shows an empty on-air state when the API returns no channels', async () => {
mockDashboardApi({ channels: [] });
render(<App />);
expect(await screen.findByText('No channels found')).toBeInTheDocument();
});
it('shows the API error detail when dashboard loading fails', async () => {
vi.spyOn(window, 'fetch').mockImplementation(() =>
Promise.resolve(new Response(
JSON.stringify({
detail: 'API write key is invalid',
status: 401,
title: 'Unauthorized'
}),
{
headers: { 'Content-Type': 'application/json' },
status: 401
}
))
);
render(<App />);
expect(await screen.findByText('API write key is invalid')).toBeInTheDocument();
});
it('exports typed primitives with expected interactions', () => {
const onSwitch = vi.fn();
const onCheckbox = vi.fn();
const onTab = vi.fn();
render(
<>
<Button variant="primary" loading>
Saving
</Button>
<Switch checked={false} onChange={onSwitch} label="Show disabled" />
<Checkbox indeterminate onChange={onCheckbox} label="Select all" />
<Input label="Channel number" value="5.1" error="Already in use" onChange={() => {}} />
<ProgressBar value={62} showLabel />
<Tabs
value="streaming"
onChange={onTab}
tabs={[{ value: 'streaming', label: 'Streaming' }]}
/>
<Tooltip label="Reset playout">
<button type="button">Reset</button>
</Tooltip>
</>
);
expect(screen.getByRole('button', { name: 'Saving' })).toBeDisabled();
fireEvent.click(screen.getByRole('switch', { name: 'Show disabled' }));
expect(onSwitch).toHaveBeenCalledWith(true);
expect(screen.getByRole('checkbox', { name: 'Select all' })).toHaveAttribute(
'aria-checked',
'mixed'
);
expect(screen.getByText('Already in use')).toBeInTheDocument();
expect(screen.getByText('62%')).toBeInTheDocument();
fireEvent.click(screen.getByRole('tab', { name: 'Streaming' }));
expect(onTab).toHaveBeenCalledWith('streaming');
fireEvent.mouseEnter(screen.getByText('Reset'));
expect(screen.getByRole('tooltip')).toHaveTextContent('Reset playout');
});
it('uses distinct semantic icons for warning and error toasts', () => {
const { container } = render(
<>
<Toast tone="warn" title="Check settings" />
<Toast tone="error" title="Save failed" />
</>
);
expect(container.querySelector('.lucide-triangle-alert')).toBeInTheDocument();
expect(container.querySelector('.lucide-circle-x')).toBeInTheDocument();
});
});
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
headers: { 'Content-Type': 'application/json' },
status
});
}
function mockDashboardApi({
channels = [],
collections = [],
schedules = [],
sessions = [],
version = { apiVersion: 3, appVersion: '26.4.0' }
}: {
channels?: unknown[];
collections?: unknown[];
schedules?: unknown[];
sessions?: unknown[];
version?: unknown;
} = {}) {
vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL) => {
const path = input.toString();
if (path === '/api/channels') {
return Promise.resolve(jsonResponse(channels));
}
if (path === '/api/collections') {
return Promise.resolve(jsonResponse(collections));
}
if (path === '/api/schedules') {
return Promise.resolve(jsonResponse(schedules));
}
if (path === '/api/sessions') {
return Promise.resolve(jsonResponse(sessions));
}
if (path === '/api/version') {
return Promise.resolve(jsonResponse(version));
}
return Promise.resolve(jsonResponse(null, 404));
});
}