test(components): cover map, collections, settings, journey and admin

This commit is contained in:
Maurice
2026-07-29 09:44:01 +02:00
committed by Maurice
parent a3b263017f
commit bbb0f93af2
124 changed files with 33011 additions and 95 deletions
@@ -0,0 +1,206 @@
// FE-W4PCON-001 to FE-W4PCON-016
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook, waitFor } from '@testing-library/react'
import { render, screen, fireEvent } from '../../../tests/helpers/render'
import type { ViewContribution } from '../../api/client'
const viewContributions = vi.fn(async (_view: string, _tripId: string | number) => ({ contributions: [] as ViewContribution[] }))
const invoke = vi.fn(async (_id: string, _sub: string, _init?: unknown) => ({}))
const toast = { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() }
vi.mock('../../api/client', () => ({
pluginsApi: {
viewContributions: (view: string, tripId: string | number) => viewContributions(view, tripId),
invoke: (id: string, sub: string, init?: unknown) => invoke(id, sub, init),
},
}))
vi.mock('../shared/Toast', () => ({ useToast: () => toast }))
vi.mock('./PluginFrame', () => ({
default: ({ pluginId, tripId, fill }: { pluginId: string; tripId: string | null; fill?: boolean }) =>
<div data-testid="frame" data-plugin={pluginId} data-trip={tripId ?? ''} data-fill={String(!!fill)} />,
}))
import { usePluginViewContributions, PluginColumns, PluginCardFooter, PluginActions } from './PluginContributions'
function column(overrides: Partial<Extract<ViewContribution, { kind: 'column' }>> = {}): ViewContribution {
return { kind: 'column', pluginId: 'p1', entityId: 1, id: 'c1', label: 'Range', value: '320 km', tone: 'default', ...overrides }
}
function action(overrides: Partial<Extract<ViewContribution, { kind: 'action' }>> = {}): ViewContribution {
return { kind: 'action', pluginId: 'p1', entityId: 1, id: 'a1', label: 'Recalculate', target: { kind: 'route', method: 'POST', sub: 'recalc' }, ...overrides }
}
beforeEach(() => {
viewContributions.mockReset()
viewContributions.mockResolvedValue({ contributions: [] })
invoke.mockReset()
invoke.mockResolvedValue({})
Object.values(toast).forEach(f => f.mockClear())
})
describe('usePluginViewContributions', () => {
it('FE-W4PCON-001: buckets contributions by entity id', async () => {
viewContributions.mockResolvedValue({
contributions: [column({ entityId: 1, id: 'a' }), column({ entityId: 2, id: 'b' }), column({ entityId: 1, id: 'c' })],
})
const { result } = renderHook(() => usePluginViewContributions('places', 4))
await waitFor(() => expect(result.current(1)).toHaveLength(2))
expect(viewContributions).toHaveBeenCalledWith('places', 4)
expect(result.current(2).map(c => c.id)).toEqual(['b'])
})
it('FE-W4PCON-002: returns a shared empty array for an entity nobody contributed to', async () => {
viewContributions.mockResolvedValue({ contributions: [column()] })
const { result } = renderHook(() => usePluginViewContributions('day', 1))
await waitFor(() => expect(result.current(1)).toHaveLength(1))
expect(result.current(77)).toBe(result.current(78))
})
it('FE-W4PCON-003: skips the request without a trip', () => {
const { result } = renderHook(() => usePluginViewContributions('costs', null))
expect(viewContributions).not.toHaveBeenCalled()
expect(result.current(1)).toEqual([])
})
it('FE-W4PCON-004: yields an empty lookup when the endpoint fails', async () => {
viewContributions.mockRejectedValue(new Error('nope'))
const { result } = renderHook(() => usePluginViewContributions('files', 1))
await waitFor(() => expect(viewContributions).toHaveBeenCalled())
expect(result.current(1)).toEqual([])
})
it('FE-W4PCON-005: tolerates a response without a contributions array', async () => {
viewContributions.mockResolvedValue({} as { contributions: ViewContribution[] })
const { result } = renderHook(() => usePluginViewContributions('todos', 1))
await waitFor(() => expect(viewContributions).toHaveBeenCalled())
expect(result.current(1)).toEqual([])
})
it('FE-W4PCON-006: refetches when the view changes', async () => {
const { rerender } = renderHook(
({ view }: { view: 'places' | 'day' }) => usePluginViewContributions(view, 1),
{ initialProps: { view: 'places' as const } },
)
await waitFor(() => expect(viewContributions).toHaveBeenCalledTimes(1))
rerender({ view: 'day' })
await waitFor(() => expect(viewContributions).toHaveBeenLastCalledWith('day', 1))
})
})
describe('PluginColumns', () => {
it('FE-W4PCON-007: renders nothing when only actions were contributed', () => {
const { container } = render(<PluginColumns items={[action()]} />)
expect(container).toBeEmptyDOMElement()
})
it('FE-W4PCON-008: renders a label/value pair with the tone class', () => {
render(<PluginColumns items={[column({ tone: 'danger' })]} />)
expect(screen.getByText('Range')).toBeInTheDocument()
expect(screen.getByText('320 km')).toHaveClass('text-danger')
})
it('FE-W4PCON-009: falls back to the muted tone for an unknown tone', () => {
render(<PluginColumns items={[column({ tone: 'weird' as Extract<ViewContribution, { kind: 'column' }>['tone'] })]} />)
expect(screen.getByText('320 km')).toHaveClass('text-content-muted')
})
it('FE-W4PCON-010: renders a url column as a new-tab link that does not open the row', () => {
render(<PluginColumns items={[column({ url: 'https://example.com' })]} />)
const link = screen.getByRole('link', { name: '320 km' })
expect(link).toHaveAttribute('href', 'https://example.com')
expect(link).toHaveAttribute('rel', 'noreferrer noopener')
const click = new MouseEvent('click', { bubbles: true, cancelable: true })
const stopped = vi.spyOn(click, 'stopPropagation')
fireEvent(link, click)
expect(stopped).toHaveBeenCalled()
})
it('FE-W4PCON-011: uses an arrow glyph for a link without a value', () => {
render(<PluginColumns items={[column({ url: 'https://example.com', value: undefined })]} />)
expect(screen.getByRole('link')).toHaveTextContent('↗')
})
})
describe('PluginActions', () => {
it('FE-W4PCON-012: renders nothing when only columns were contributed', () => {
const { container } = render(<PluginActions items={[column()]} tripId={1} />)
expect(container).toBeEmptyDOMElement()
})
it('FE-W4PCON-013: a route action invokes the plugin and toasts on success', async () => {
render(<PluginActions items={[action()]} tripId={1} />)
fireEvent.click(screen.getByRole('button', { name: 'Recalculate' }))
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Recalculate'))
expect(invoke).toHaveBeenCalledWith('p1', 'recalc', { method: 'POST' })
})
it('FE-W4PCON-014: a failing route action toasts the error', async () => {
invoke.mockRejectedValue(new Error('500'))
render(<PluginActions items={[action()]} tripId={1} />)
fireEvent.click(screen.getByRole('button', { name: 'Recalculate' }))
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Recalculate'))
})
it('FE-W4PCON-015: a frame action opens the sandboxed modal and closes on the X', () => {
render(<PluginActions items={[action({ label: 'Configure', target: { kind: 'frame', sub: 'config' } })]} tripId={9} />)
fireEvent.click(screen.getByRole('button', { name: 'Configure' }))
const frame = screen.getByTestId('frame')
expect(frame).toHaveAttribute('data-plugin', 'p1')
expect(frame).toHaveAttribute('data-trip', '9')
expect(frame).toHaveAttribute('data-fill', 'true')
expect(invoke).not.toHaveBeenCalled()
fireEvent.click(screen.getAllByRole('button')[1])
expect(screen.queryByTestId('frame')).toBeNull()
})
it('FE-W4PCON-016: the frame modal closes on backdrop click but not on card click', () => {
const { container } = render(
<PluginActions items={[action({ label: 'Configure', target: { kind: 'frame', sub: 'config' } })]} tripId={null} />,
)
fireEvent.click(screen.getByRole('button', { name: 'Configure' }))
expect(screen.getByTestId('frame')).toHaveAttribute('data-trip', '')
fireEvent.click(container.querySelector('.bg-surface-card')!)
expect(screen.getByTestId('frame')).toBeInTheDocument()
fireEvent.click(container.querySelector('.fixed.inset-0')!)
expect(screen.queryByTestId('frame')).toBeNull()
})
it('FE-W4PCON-017: accepts a caller className for the action buttons', () => {
render(<PluginActions items={[action()]} tripId={1} className="btn-sm" />)
expect(screen.getByRole('button', { name: 'Recalculate' })).toHaveClass('btn-sm')
})
})
describe('PluginCardFooter', () => {
it('FE-W4PCON-018: renders nothing without contributions', () => {
const { container } = render(<PluginCardFooter items={[]} tripId={1} />)
expect(container).toBeEmptyDOMElement()
})
it('FE-W4PCON-019: renders columns and actions together under a divider', () => {
render(<PluginCardFooter items={[column(), action()]} tripId={1} />)
expect(screen.getByText('Range')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Recalculate' })).toBeInTheDocument()
})
})
@@ -0,0 +1,165 @@
// FE-W4PDS-001 to FE-W4PDS-013
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook, waitFor } from '@testing-library/react'
import { render, screen } from '../../../tests/helpers/render'
import type { PluginDayScheduleItem } from '../../api/client'
const daySchedule = vi.fn(async (_tripId: number | string) => ({ items: [] as PluginDayScheduleItem[] }))
vi.mock('../../api/client', () => ({
pluginsApi: { daySchedule: (tripId: number | string) => daySchedule(tripId) },
}))
import { usePluginDaySchedule, formatScheduleMinutes, PluginDayScheduleRow } from './PluginDaySchedule'
function item(overrides: Partial<PluginDayScheduleItem> = {}): PluginDayScheduleItem {
return { pluginId: 'ev', id: 'i1', dayId: 1, label: 'Charging', tone: 'default', ...overrides }
}
beforeEach(() => {
daySchedule.mockReset()
daySchedule.mockResolvedValue({ items: [] })
})
describe('formatScheduleMinutes', () => {
it('FE-W4PDS-001: formats sub-hour durations in minutes', () => {
expect(formatScheduleMinutes(35)).toBe('35 min')
expect(formatScheduleMinutes(0)).toBe('0 min')
})
it('FE-W4PDS-002: splits an hour or more into h + min', () => {
expect(formatScheduleMinutes(60)).toBe('1 h 0 min')
expect(formatScheduleMinutes(95)).toBe('1 h 35 min')
expect(formatScheduleMinutes(1440)).toBe('24 h 0 min')
})
})
describe('usePluginDaySchedule', () => {
it('FE-W4PDS-003: returns the shared empty schedule without a trip', () => {
const { result } = renderHook(() => usePluginDaySchedule(null))
expect(daySchedule).not.toHaveBeenCalled()
expect(result.current).toEqual({ byAssignment: {}, byReservation: {}, byPosition: {}, minutesByDay: {} })
})
it('FE-W4PDS-004: groups place-anchored rows by day and assignment', async () => {
daySchedule.mockResolvedValue({
items: [
item({ id: 'a', dayId: 3, assignmentId: 10, minutes: 35 }),
item({ id: 'b', dayId: 3, assignmentId: 10, minutes: 5 }),
item({ id: 'c', dayId: 3, assignmentId: 11 }),
],
})
const { result } = renderHook(() => usePluginDaySchedule(7))
await waitFor(() => expect(result.current.byAssignment[3]).toBeDefined())
expect(result.current.byAssignment[3][10].map(i => i.id)).toEqual(['a', 'b'])
expect(result.current.byAssignment[3][11].map(i => i.id)).toEqual(['c'])
expect(daySchedule).toHaveBeenCalledWith(7)
})
it('FE-W4PDS-005: groups booking-anchored rows by day and reservation', async () => {
daySchedule.mockResolvedValue({
items: [
item({ id: 'a', dayId: 2, reservationId: 55, minutes: 45 }),
item({ id: 'b', dayId: 2, reservationId: 55 }),
],
})
const { result } = renderHook(() => usePluginDaySchedule(1))
await waitFor(() => expect(result.current.byReservation[2]).toBeDefined())
expect(result.current.byReservation[2][55].map(i => i.id)).toEqual(['a', 'b'])
})
it('FE-W4PDS-006: pins unanchored rows to the start or end of the day', async () => {
daySchedule.mockResolvedValue({
items: [
item({ id: 'first', dayId: 4, position: 'start' }),
item({ id: 'last', dayId: 4, position: 'end' }),
item({ id: 'default', dayId: 4 }),
],
})
const { result } = renderHook(() => usePluginDaySchedule(1))
await waitFor(() => expect(result.current.byPosition[4]).toBeDefined())
expect(result.current.byPosition[4].start.map(i => i.id)).toEqual(['first'])
expect(result.current.byPosition[4].end.map(i => i.id)).toEqual(['last', 'default'])
})
it('FE-W4PDS-007: sums the contributed minutes per day', async () => {
daySchedule.mockResolvedValue({
items: [
item({ id: 'a', dayId: 1, assignmentId: 1, minutes: 35 }),
item({ id: 'b', dayId: 1, reservationId: 2, minutes: 45 }),
item({ id: 'c', dayId: 2, minutes: 10 }),
item({ id: 'd', dayId: 2 }),
],
})
const { result } = renderHook(() => usePluginDaySchedule(1))
await waitFor(() => expect(result.current.minutesByDay[1]).toBe(80))
expect(result.current.minutesByDay[2]).toBe(10)
})
it('FE-W4PDS-008: prefers the assignment anchor when both ids are present', async () => {
daySchedule.mockResolvedValue({ items: [item({ dayId: 1, assignmentId: 9, reservationId: 8 })] })
const { result } = renderHook(() => usePluginDaySchedule(1))
await waitFor(() => expect(result.current.byAssignment[1]).toBeDefined())
expect(result.current.byReservation).toEqual({})
})
it('FE-W4PDS-009: falls back to no extra rows when the endpoint fails', async () => {
daySchedule.mockRejectedValue(new Error('offline'))
const { result } = renderHook(() => usePluginDaySchedule(1))
await waitFor(() => expect(daySchedule).toHaveBeenCalled())
expect(result.current.minutesByDay).toEqual({})
})
it('FE-W4PDS-010: tolerates a response without an items array', async () => {
daySchedule.mockResolvedValue({} as { items: PluginDayScheduleItem[] })
const { result } = renderHook(() => usePluginDaySchedule(1))
await waitFor(() => expect(daySchedule).toHaveBeenCalled())
expect(result.current.byPosition).toEqual({})
})
it('FE-W4PDS-011: refetches when the trip changes', async () => {
const { rerender } = renderHook(({ id }: { id: number }) => usePluginDaySchedule(id), { initialProps: { id: 1 } })
await waitFor(() => expect(daySchedule).toHaveBeenCalledTimes(1))
rerender({ id: 2 })
await waitFor(() => expect(daySchedule).toHaveBeenLastCalledWith(2))
})
})
describe('PluginDayScheduleRow', () => {
it('FE-W4PDS-012: renders the duration, separator and label', () => {
render(<PluginDayScheduleRow item={item({ minutes: 95, label: 'Charging stop' })} />)
expect(screen.getByText('1 h 35 min')).toBeInTheDocument()
expect(screen.getByText('·')).toBeInTheDocument()
expect(screen.getByText('Charging stop')).toBeInTheDocument()
})
it('FE-W4PDS-013: drops the duration when the plugin contributes none', () => {
render(<PluginDayScheduleRow item={item({ label: 'Security check' })} />)
expect(screen.getByText('Security check')).toBeInTheDocument()
expect(screen.queryByText('·')).toBeNull()
})
it('FE-W4PDS-014: colours the icon by tone and falls back for an unknown tone', () => {
const { container, unmount } = render(<PluginDayScheduleRow item={item({ tone: 'danger' })} />)
expect((container.querySelector('svg') as SVGElement).style.color).toBe('rgb(239, 68, 68)')
unmount()
const odd = render(<PluginDayScheduleRow item={item({ tone: 'nope' as PluginDayScheduleItem['tone'] })} />)
expect((odd.container.querySelector('svg') as SVGElement).style.color).toBe('rgb(79, 70, 229)')
})
})
@@ -1,4 +1,4 @@
// FE-PLUGINS-FRAME-001 to 012
// FE-PLUGINS-FRAME-001 to 046
import { render, cleanup, waitFor, fireEvent, screen, act } from '@testing-library/react';
import PluginFrame from './PluginFrame';
import { usePluginStore } from '../../store/pluginStore';
@@ -8,11 +8,22 @@ const toast = { info: vi.fn(), success: vi.fn(), warning: vi.fn(), error: vi.fn(
const invoke = vi.fn((..._args: unknown[]) => Promise.resolve({ ok: true }));
const wsListeners = new Set<(ev: Record<string, unknown>) => void>();
// Host state the frame mirrors into its context. Mutable so a single test can
// change one input (no user, another currency) without a second mock factory.
const DEFAULT_USER = { id: 7, username: 'ada', avatar_url: null, role: 'admin' };
const DEFAULT_SETTINGS = { default_currency: 'EUR', time_format: '24h', distance_unit: 'metric', temperature_unit: 'celsius', blur_booking_codes: true };
const host = vi.hoisted(() => ({
user: { id: 7, username: 'ada', avatar_url: null, role: 'admin' } as Record<string, unknown> | null,
settings: { default_currency: 'EUR', time_format: '24h', distance_unit: 'metric', temperature_unit: 'celsius', blur_booking_codes: true } as Record<string, unknown>,
trip: null as Record<string, unknown> | null,
}));
vi.mock('react-router-dom', () => ({ useNavigate: () => navigate }));
vi.mock('../shared/Toast', () => ({ useToast: () => toast }));
vi.mock('../../i18n', () => ({ useTranslation: () => ({ locale: 'en', t: (k: string) => k }) }));
vi.mock('../../store/authStore', () => ({ useAuthStore: (sel: (s: unknown) => unknown) => sel({ user: { id: 7, username: 'ada', avatar_url: null, role: 'admin' } }) }));
vi.mock('../../store/settingsStore', () => ({ useSettingsStore: (sel: (s: unknown) => unknown) => sel({ settings: { default_currency: 'EUR', time_format: '24h', distance_unit: 'metric', temperature_unit: 'celsius', blur_booking_codes: true } }) }));
vi.mock('../../store/authStore', () => ({ useAuthStore: (sel: (s: unknown) => unknown) => sel({ user: host.user }) }));
vi.mock('../../store/settingsStore', () => ({ useSettingsStore: (sel: (s: unknown) => unknown) => sel({ settings: host.settings }) }));
vi.mock('../../store/tripStore', () => ({ useTripStore: (sel: (s: unknown) => unknown) => sel({ trip: host.trip }) }));
vi.mock('../../api/client', () => ({ pluginsApi: { invoke: (id: string, sub: string, init?: unknown) => invoke(id, sub, init) } }));
vi.mock('../../api/websocket', () => ({
addListener: (fn: (ev: Record<string, unknown>) => void) => wsListeners.add(fn),
@@ -23,6 +34,19 @@ function fromFrame(frame: HTMLIFrameElement, data: unknown) {
window.dispatchEvent(new MessageEvent('message', { source: frame.contentWindow, data } as MessageEventInit));
}
/** Mount a frame and capture everything the host posts into it. */
function mountFrame(props: Partial<Parameters<typeof PluginFrame>[0]> = {}) {
const view = render(<PluginFrame pluginId="demo" {...props} />);
const iframe = view.container.querySelector('iframe')!;
const posted: Array<Record<string, unknown>> = [];
(iframe.contentWindow as unknown as { postMessage: (m: unknown) => void }).postMessage = (m: unknown) =>
posted.push(m as Record<string, unknown>);
return { ...view, iframe, posted };
}
const answerFor = (posted: Array<Record<string, unknown>>, requestId: string) =>
posted.find((m) => m.requestId === requestId);
afterEach(() => {
cleanup();
sessionStorage.clear();
@@ -30,6 +54,17 @@ afterEach(() => {
Object.values(toast).forEach((f) => f.mockClear());
invoke.mockClear();
wsListeners.clear();
host.user = { ...DEFAULT_USER };
host.settings = { ...DEFAULT_SETTINGS };
host.trip = null;
const html = document.documentElement;
html.classList.remove('dark');
html.removeAttribute('dir');
html.removeAttribute('style');
html.removeAttribute('data-scheme');
html.removeAttribute('data-density');
html.removeAttribute('data-no-transparency');
html.removeAttribute('data-reduce-motion');
});
describe('PluginFrame', () => {
@@ -317,6 +352,66 @@ describe('PluginFrame', () => {
expect(posted.length).toBe(before);
expect(geo.clearWatch).toHaveBeenCalledWith(7);
});
it('FE-PLUGINS-FRAME-023: a request without a requestId is dropped before the browser API', () => {
const { iframe, posted } = mount(true);
fromFrame(iframe, { type: 'trek:geolocation' });
fromFrame(iframe, { type: 'trek:geolocation', requestId: '' });
expect(posted.filter((m) => m.type === 'trek:geolocation:result')).toHaveLength(0);
expect(geo.getCurrentPosition).not.toHaveBeenCalled();
});
it('FE-PLUGINS-FRAME-024: reports "unsupported" when the browser has no geolocation', () => {
const own = Object.getOwnPropertyDescriptor(navigator, 'geolocation');
delete (navigator as unknown as { geolocation?: unknown }).geolocation;
try {
const { iframe, posted } = mount(true);
fromFrame(iframe, { type: 'trek:geolocation', requestId: 'g7' });
expect(answerFor(posted, 'g7')).toMatchObject({ error: 'unsupported' });
} finally {
if (own) Object.defineProperty(navigator, 'geolocation', own);
}
});
it('FE-PLUGINS-FRAME-025: maps the browser error codes onto the bridge vocabulary', () => {
const codes: Array<[number, string]> = [[1, 'denied'], [3, 'timeout'], [2, 'unavailable']];
for (const [code, expected] of codes) {
geo.getCurrentPosition.mockImplementation((_ok: unknown, fail: (e: unknown) => void) =>
fail({ code, PERMISSION_DENIED: 1, POSITION_UNAVAILABLE: 2, TIMEOUT: 3 }));
const { iframe, posted, unmount } = mount(true);
fromFrame(iframe, { type: 'trek:geolocation', requestId: `e${code}` });
expect(answerFor(posted, `e${code}`)).toMatchObject({ error: expected });
unmount();
}
});
it('FE-PLUGINS-FRAME-026: a watch error is streamed as an update, not a result', () => {
let boom: ((e: unknown) => void) | null = null;
geo.watchPosition.mockImplementation((_ok: unknown, fail: (e: unknown) => void) => { boom = fail; return 7; });
const { iframe, posted } = mount(true);
fromFrame(iframe, { type: 'trek:geolocation', requestId: 'g8', action: 'watch' });
act(() => boom!({ code: 3, PERMISSION_DENIED: 1, TIMEOUT: 3 }));
expect(posted.find((m) => m.type === 'trek:geolocation:update')).toMatchObject({ error: 'timeout' });
});
it('FE-PLUGINS-FRAME-027: a second watch replaces the first one', () => {
const { iframe } = mount(true);
fromFrame(iframe, { type: 'trek:geolocation', requestId: 'g9', action: 'watch' });
expect(geo.clearWatch).not.toHaveBeenCalled();
fromFrame(iframe, { type: 'trek:geolocation', requestId: 'g10', action: 'watch' });
expect(geo.clearWatch).toHaveBeenCalledWith(7);
expect(geo.watchPosition).toHaveBeenCalledTimes(2);
});
it('FE-PLUGINS-FRAME-028: clear without a running watch still confirms', () => {
const { iframe, posted } = mount(true);
fromFrame(iframe, { type: 'trek:geolocation', requestId: 'g11', action: 'clear' });
expect(geo.clearWatch).not.toHaveBeenCalled();
expect(answerFor(posted, 'g11')).toMatchObject({ cleared: true });
});
});
it('FE-PLUGINS-FRAME-020: brokered plugin session state round-trips through host sessionStorage', () => {
@@ -0,0 +1,59 @@
// FE-W4PW-001 to FE-W4PW-005
import { describe, it, expect, vi } from 'vitest'
import { render, screen } from '../../../tests/helpers/render'
import type { ActivePlugin } from '../../store/pluginStore'
vi.mock('./PluginFrame', () => ({
default: ({ pluginId, tripId, title }: { pluginId: string; tripId: string | null; title?: string }) =>
<div data-testid="frame" data-plugin={pluginId} data-trip={tripId ?? ''} data-title={title} />,
}))
import PluginWidgets from './PluginWidgets'
function plugin(overrides: Partial<ActivePlugin> = {}): ActivePlugin {
return { id: 'weather', name: 'Weather', icon: 'CloudSun', ...overrides } as unknown as ActivePlugin
}
describe('PluginWidgets', () => {
it('FE-W4PW-001: renders nothing without active widget plugins', () => {
const { container } = render(<PluginWidgets plugins={[]} />)
expect(container).toBeEmptyDOMElement()
})
it('FE-W4PW-002: renders one card per plugin with its name', () => {
render(<PluginWidgets plugins={[plugin(), plugin({ id: 'fx', name: 'Currency' })]} />)
expect(screen.getByText('Weather')).toBeInTheDocument()
expect(screen.getByText('Currency')).toBeInTheDocument()
expect(screen.getAllByTestId('frame')).toHaveLength(2)
})
it('FE-W4PW-003: hands each card its own sandboxed frame', () => {
render(<PluginWidgets plugins={[plugin()]} />)
const frame = screen.getByTestId('frame')
expect(frame).toHaveAttribute('data-plugin', 'weather')
expect(frame).toHaveAttribute('data-title', 'Weather')
})
it('FE-W4PW-004: defaults the trip context to null and forwards a given tripId', () => {
const { unmount } = render(<PluginWidgets plugins={[plugin()]} />)
expect(screen.getByTestId('frame')).toHaveAttribute('data-trip', '')
unmount()
render(<PluginWidgets plugins={[plugin()]} tripId="42" />)
expect(screen.getByTestId('frame')).toHaveAttribute('data-trip', '42')
})
it('FE-W4PW-005: gives the body a pre-resize minimum height', () => {
render(<PluginWidgets plugins={[plugin()]} />)
expect(screen.getByTestId('frame').parentElement).toHaveStyle({ minHeight: '60px' })
})
it('FE-W4PW-006: renders the plugin icon in the card header', () => {
const { container } = render(<PluginWidgets plugins={[plugin()]} />)
expect(container.querySelector('.lucide-cloud-sun')).not.toBeNull()
})
})
@@ -0,0 +1,122 @@
// FE-W4TCB-001 to FE-W4TCB-011
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook, waitFor } from '@testing-library/react'
import { render, screen, fireEvent } from '../../../tests/helpers/render'
import type { TripCardBadge } from '../../api/client'
const tripCardContributions = vi.fn(async (_ids: Array<number | string>) => ({ contributions: [] as TripCardBadge[] }))
vi.mock('../../api/client', () => ({
pluginsApi: { tripCardContributions: (ids: Array<number | string>) => tripCardContributions(ids) },
}))
import { TripCardBadges, useTripCardBadges } from './TripCardBadges'
function badge(overrides: Partial<TripCardBadge> = {}): TripCardBadge {
return { pluginId: 'p1', tripId: 1, id: 'b1', label: 'CO2', value: '12 kg', tone: 'default', ...overrides }
}
beforeEach(() => {
tripCardContributions.mockReset()
tripCardContributions.mockResolvedValue({ contributions: [] })
})
describe('useTripCardBadges', () => {
it('FE-W4TCB-001: fetches all visible trip ids in one call and buckets by trip', async () => {
tripCardContributions.mockResolvedValue({
contributions: [
badge({ tripId: 1, id: 'a' }),
badge({ tripId: 2, id: 'b' }),
badge({ tripId: 1, id: 'c' }),
],
})
const { result } = renderHook(() => useTripCardBadges([1, 2], true))
await waitFor(() => expect(result.current(1)).toHaveLength(2))
expect(tripCardContributions).toHaveBeenCalledExactlyOnceWith([1, 2])
expect(result.current(1).map(b => b.id)).toEqual(['a', 'c'])
expect(result.current(2).map(b => b.id)).toEqual(['b'])
})
it('FE-W4TCB-002: returns a stable empty array for a trip with no badges', async () => {
tripCardContributions.mockResolvedValue({ contributions: [badge({ tripId: 1 })] })
const { result } = renderHook(() => useTripCardBadges([1], true))
await waitFor(() => expect(result.current(1)).toHaveLength(1))
expect(result.current(99)).toBe(result.current(98))
})
it('FE-W4TCB-003: never hits the endpoint when no plugin is active', () => {
renderHook(() => useTripCardBadges([1, 2], false))
expect(tripCardContributions).not.toHaveBeenCalled()
})
it('FE-W4TCB-004: never hits the endpoint for an empty dashboard', () => {
renderHook(() => useTripCardBadges([], true))
expect(tripCardContributions).not.toHaveBeenCalled()
})
it('FE-W4TCB-005: yields an empty lookup when the endpoint fails', async () => {
tripCardContributions.mockRejectedValue(new Error('boom'))
const { result } = renderHook(() => useTripCardBadges([1], true))
await waitFor(() => expect(tripCardContributions).toHaveBeenCalled())
expect(result.current(1)).toEqual([])
})
it('FE-W4TCB-006: tolerates a response without a contributions array', async () => {
tripCardContributions.mockResolvedValue({} as { contributions: TripCardBadge[] })
const { result } = renderHook(() => useTripCardBadges([1], true))
await waitFor(() => expect(tripCardContributions).toHaveBeenCalled())
expect(result.current(1)).toEqual([])
})
it('FE-W4TCB-007: refetches when the visible id set changes', async () => {
const { rerender } = renderHook(({ ids }: { ids: number[] }) => useTripCardBadges(ids, true), {
initialProps: { ids: [1] },
})
await waitFor(() => expect(tripCardContributions).toHaveBeenCalledTimes(1))
rerender({ ids: [1, 2] })
await waitFor(() => expect(tripCardContributions).toHaveBeenCalledTimes(2))
expect(tripCardContributions).toHaveBeenLastCalledWith([1, 2])
})
})
describe('TripCardBadges', () => {
it('FE-W4TCB-008: renders nothing when no plugin contributes', () => {
const { container } = render(<TripCardBadges items={[]} />)
expect(container).toBeEmptyDOMElement()
})
it('FE-W4TCB-009: renders a plain chip with label, value and tone class', () => {
const { container } = render(<TripCardBadges items={[badge({ tone: 'warn' })]} />)
expect(screen.getByText('CO2')).toBeInTheDocument()
expect(screen.getByText('12 kg')).toBeInTheDocument()
expect(container.querySelector('.trip-plugin-badge')).toHaveClass('tone-warn')
})
it('FE-W4TCB-010: omits the value span when the badge carries none', () => {
const { container } = render(<TripCardBadges items={[badge({ value: undefined }), badge({ id: 'b2', value: '' })]} />)
expect(container.querySelectorAll('.badge-value')).toHaveLength(0)
expect(container.querySelectorAll('.badge-label')).toHaveLength(2)
})
it('FE-W4TCB-011: renders a url badge as a safe new-tab link that does not open the card', () => {
render(<TripCardBadges items={[badge({ url: 'https://example.com/report' })]} />)
const link = screen.getByRole('link')
expect(link).toHaveAttribute('href', 'https://example.com/report')
expect(link).toHaveAttribute('target', '_blank')
expect(link).toHaveAttribute('rel', 'noreferrer noopener')
const click = new MouseEvent('click', { bubbles: true, cancelable: true })
const stopped = vi.spyOn(click, 'stopPropagation')
fireEvent(link, click)
expect(stopped).toHaveBeenCalled()
})
})