mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 09:38:54 +00:00
test(mobile): cover admin, settings and the remaining screens
This commit is contained in:
@@ -1,9 +1,14 @@
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { Route, Routes } from 'react-router-dom';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { fireEvent, render, screen, waitFor } from '../../../helpers/render';
|
||||
import { server } from '../../../helpers/msw/server';
|
||||
import { resetAllStores, seedStore } from '../../../helpers/store';
|
||||
import { buildAdmin } from '../../../helpers/factories';
|
||||
import { useAuthStore } from '../../../../src/store/authStore';
|
||||
import { useAddonStore } from '../../../../src/store/addonStore';
|
||||
import { ToastContainer } from '../../../../src/components/shared/Toast';
|
||||
import MAdmin from '../../../../src/mobile/screens/admin/MAdmin';
|
||||
|
||||
// FE-MOB-ADMIN-001 onwards
|
||||
@@ -14,9 +19,99 @@ vi.mock('../../../../src/mobile/screens/admin/MAdminPermissionsPanel', () => ({
|
||||
default: () => <div data-testid="permissions-panel" />,
|
||||
}));
|
||||
|
||||
// Every other section panel has its own suite; here only the routing into them
|
||||
// matters, so they are reduced to markers.
|
||||
vi.mock('../../../../src/mobile/screens/admin/MAdminPluginsPanel', () => ({
|
||||
default: () => <div data-testid="plugins-panel" />,
|
||||
}));
|
||||
vi.mock('../../../../src/mobile/screens/admin/MAdminBackupPanel', () => ({
|
||||
default: () => <div data-testid="backup-panel" />,
|
||||
}));
|
||||
vi.mock('../../../../src/mobile/screens/admin/MAdminCategoryManager', () => ({
|
||||
default: () => <div data-testid="category-manager" />,
|
||||
}));
|
||||
vi.mock('../../../../src/mobile/screens/admin/MAdminPackingTemplateManager', () => ({
|
||||
default: () => <div data-testid="packing-templates" />,
|
||||
}));
|
||||
vi.mock('../../../../src/mobile/screens/admin/MAdminDefaultUserSettings', () => ({
|
||||
default: () => <div data-testid="default-user-settings" />,
|
||||
}));
|
||||
vi.mock('../../../../src/mobile/screens/admin/MAdminDevNotificationsPanel', () => ({
|
||||
default: () => <div data-testid="dev-notifications" />,
|
||||
}));
|
||||
vi.mock('../../../../src/mobile/screens/admin/MAdminNotificationsSection', () => ({
|
||||
default: () => <div data-testid="notifications-section" />,
|
||||
}));
|
||||
vi.mock('../../../../src/mobile/screens/admin/MAdminMcpTokensPanel', () => ({
|
||||
default: () => <div data-testid="mcp-tokens-panel" />,
|
||||
}));
|
||||
vi.mock('../../../../src/mobile/screens/admin/MAdminAuditLogPanel', () => ({
|
||||
default: ({ serverTimezone }: { serverTimezone?: string }) => (
|
||||
<div data-testid="audit-panel">{serverTimezone}</div>
|
||||
),
|
||||
}));
|
||||
vi.mock('../../../../src/mobile/screens/admin/MAdminGitHubPanel', () => ({
|
||||
default: ({ isPrerelease }: { isPrerelease: boolean }) => (
|
||||
<div data-testid="github-panel">{String(isPrerelease)}</div>
|
||||
),
|
||||
}));
|
||||
|
||||
// The addon manager is reduced to the two controls MAdmin wires itself.
|
||||
vi.mock('../../../../src/mobile/screens/admin/MAdminAddonManager', () => ({
|
||||
default: ({
|
||||
bagTrackingEnabled,
|
||||
onToggleBagTracking,
|
||||
collabFeatures,
|
||||
onToggleCollabFeature,
|
||||
}: {
|
||||
bagTrackingEnabled: boolean;
|
||||
onToggleBagTracking: () => void;
|
||||
collabFeatures: Record<string, boolean>;
|
||||
onToggleCollabFeature: (key: string) => void;
|
||||
}) => (
|
||||
<div>
|
||||
<span data-testid="bag-state">{String(bagTrackingEnabled)}</span>
|
||||
<button type="button" onClick={onToggleBagTracking}>toggle bag</button>
|
||||
<span data-testid="chat-state">{String(collabFeatures.chat)}</span>
|
||||
<button type="button" onClick={() => onToggleCollabFeature('chat')}>toggle chat</button>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
function renderAdmin() {
|
||||
return render(
|
||||
<>
|
||||
<ToastContainer />
|
||||
<Routes>
|
||||
<Route path="/admin" element={<MAdmin />} />
|
||||
<Route path="/dashboard" element={<div>dashboard page</div>} />
|
||||
</Routes>
|
||||
</>,
|
||||
{ initialEntries: ['/admin'] },
|
||||
);
|
||||
}
|
||||
|
||||
async function openSection(label: string) {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Administration' }));
|
||||
fireEvent.click(screen.getByRole('button', { name: label }));
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
|
||||
server.use(
|
||||
http.get('/api/admin/collab-features', () =>
|
||||
HttpResponse.json({ chat: true, notes: true, polls: true, whatsnext: true }),
|
||||
),
|
||||
http.get('/api/admin/places-photos', () => HttpResponse.json({ enabled: false })),
|
||||
http.get('/api/admin/places-autocomplete', () => HttpResponse.json({ enabled: false })),
|
||||
http.get('/api/admin/places-details', () => HttpResponse.json({ enabled: false })),
|
||||
http.get('/api/admin/invites/trips', () => HttpResponse.json({ trips: [] })),
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
describe('MAdmin', () => {
|
||||
@@ -51,4 +146,227 @@ describe('MAdmin', () => {
|
||||
await waitFor(() => expect(screen.getByText('Authentication Methods')).toBeInTheDocument());
|
||||
expect(screen.queryByText('alice')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ADMIN-003: the back button leaves for the dashboard', async () => {
|
||||
renderAdmin();
|
||||
await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument());
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Back' }));
|
||||
|
||||
expect(screen.getByText('dashboard page')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ADMIN-004: the header plus opens the create-user sheet', async () => {
|
||||
renderAdmin();
|
||||
await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument());
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Create User' }));
|
||||
|
||||
expect(screen.getByRole('dialog', { name: 'Create User' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ADMIN-005: MCP Access and the dev section stay hidden unless enabled', async () => {
|
||||
renderAdmin();
|
||||
await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument());
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Administration' }));
|
||||
|
||||
expect(screen.queryByRole('button', { name: 'MCP Access' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Dev: Notifications' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ADMIN-006: the MCP addon adds its section to the dropdown', async () => {
|
||||
useAddonStore.setState({
|
||||
addons: [{ id: 'mcp', name: 'MCP', type: 'integration', icon: 'plug', enabled: true }],
|
||||
bagTracking: false,
|
||||
loaded: true,
|
||||
});
|
||||
renderAdmin();
|
||||
await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument());
|
||||
|
||||
await openSection('MCP Access');
|
||||
|
||||
expect(screen.getByTestId('mcp-tokens-panel')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ADMIN-007: dev mode adds the dev notifications section', async () => {
|
||||
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin(), devMode: true });
|
||||
renderAdmin();
|
||||
await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument());
|
||||
|
||||
await openSection('Dev: Notifications');
|
||||
|
||||
expect(screen.getByTestId('dev-notifications')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ADMIN-008: every remaining section is reachable from the dropdown', async () => {
|
||||
renderAdmin();
|
||||
await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument());
|
||||
|
||||
await openSection('User Defaults');
|
||||
expect(screen.getByTestId('default-user-settings')).toBeInTheDocument();
|
||||
|
||||
await openSection('Personalization');
|
||||
expect(screen.getByTestId('packing-templates')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('category-manager')).toBeInTheDocument();
|
||||
|
||||
await openSection('Plugins');
|
||||
expect(screen.getByTestId('plugins-panel')).toBeInTheDocument();
|
||||
|
||||
await openSection('Notifications');
|
||||
expect(screen.getByTestId('notifications-section')).toBeInTheDocument();
|
||||
|
||||
await openSection('Backup');
|
||||
expect(screen.getByTestId('backup-panel')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ADMIN-009: the audit and GitHub panels get the server timezone and prerelease flag', async () => {
|
||||
server.use(
|
||||
http.get('/api/admin/version-check', () =>
|
||||
HttpResponse.json({
|
||||
update_available: true,
|
||||
latest: '3.5.0',
|
||||
current: '3.4.0',
|
||||
is_prerelease: true,
|
||||
is_docker: true,
|
||||
}),
|
||||
),
|
||||
);
|
||||
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin(), serverTimezone: 'Europe/Berlin' });
|
||||
renderAdmin();
|
||||
await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument());
|
||||
|
||||
await openSection('Audit');
|
||||
expect(screen.getByTestId('audit-panel')).toHaveTextContent('Europe/Berlin');
|
||||
|
||||
await openSection('GitHub');
|
||||
await waitFor(() => expect(screen.getByTestId('github-panel')).toHaveTextContent('true'));
|
||||
});
|
||||
|
||||
it('FE-MOB-ADMIN-010: the update banner opens the how-to-update sheet', async () => {
|
||||
server.use(
|
||||
http.get('/api/admin/version-check', () =>
|
||||
HttpResponse.json({ update_available: true, latest: '3.5.0', current: '3.4.0', is_docker: true }),
|
||||
),
|
||||
);
|
||||
renderAdmin();
|
||||
|
||||
await screen.findByText('Update available');
|
||||
expect(screen.getByText('Version v3.5.0 available · you have v3.4.0')).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Update' }));
|
||||
|
||||
expect(screen.getByRole('dialog', { name: 'How to Update' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ADMIN-011: no banner when the version check reports no update', async () => {
|
||||
renderAdmin();
|
||||
await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument());
|
||||
|
||||
expect(screen.queryByText('Update available')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ADMIN-012: demo instances can save a baseline', async () => {
|
||||
let saved = false;
|
||||
server.use(
|
||||
http.post('/api/admin/save-demo-baseline', () => {
|
||||
saved = true;
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin(), demoMode: true });
|
||||
renderAdmin();
|
||||
await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument());
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save Baseline' }));
|
||||
|
||||
await screen.findByText('Baseline saved! Resets will restore to this state.');
|
||||
expect(saved).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-MOB-ADMIN-013: a failing baseline save surfaces the server message', async () => {
|
||||
server.use(
|
||||
http.post('/api/admin/save-demo-baseline', () =>
|
||||
HttpResponse.json({ error: 'Not a demo instance' }, { status: 400 }),
|
||||
),
|
||||
);
|
||||
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin(), demoMode: true });
|
||||
renderAdmin();
|
||||
await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument());
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save Baseline' }));
|
||||
|
||||
await screen.findByText('Not a demo instance');
|
||||
});
|
||||
|
||||
it('FE-MOB-ADMIN-014: the bag tracking toggle persists and rolls back on failure', async () => {
|
||||
const bodies: unknown[] = [];
|
||||
server.use(
|
||||
http.put('/api/admin/bag-tracking', async ({ request }) => {
|
||||
bodies.push(await request.json());
|
||||
return bodies.length === 1
|
||||
? HttpResponse.json({ enabled: true })
|
||||
: HttpResponse.json({ error: 'boom' }, { status: 500 });
|
||||
}),
|
||||
);
|
||||
renderAdmin();
|
||||
await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument());
|
||||
await openSection('Addons');
|
||||
|
||||
expect(screen.getByTestId('bag-state')).toHaveTextContent('false');
|
||||
fireEvent.click(screen.getByRole('button', { name: 'toggle bag' }));
|
||||
await waitFor(() => expect(screen.getByTestId('bag-state')).toHaveTextContent('true'));
|
||||
|
||||
// Second call fails → the optimistic value is reverted
|
||||
fireEvent.click(screen.getByRole('button', { name: 'toggle bag' }));
|
||||
await waitFor(() => expect(screen.getByTestId('bag-state')).toHaveTextContent('true'));
|
||||
expect(bodies).toEqual([{ enabled: true }, { enabled: false }]);
|
||||
});
|
||||
|
||||
it('FE-MOB-ADMIN-015: a collab feature toggle sends only the changed key', async () => {
|
||||
let sent: Record<string, unknown> = {};
|
||||
server.use(
|
||||
http.put('/api/admin/collab-features', async ({ request }) => {
|
||||
sent = (await request.json()) as Record<string, unknown>;
|
||||
return HttpResponse.json({ ...sent });
|
||||
}),
|
||||
);
|
||||
renderAdmin();
|
||||
await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument());
|
||||
await openSection('Addons');
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('chat-state')).toHaveTextContent('true'));
|
||||
fireEvent.click(screen.getByRole('button', { name: 'toggle chat' }));
|
||||
|
||||
await waitFor(() => expect(sent).toEqual({ chat: false }));
|
||||
expect(screen.getByTestId('chat-state')).toHaveTextContent('false');
|
||||
});
|
||||
|
||||
it('FE-MOB-ADMIN-016: a failing collab update restores the previous flags', async () => {
|
||||
server.use(
|
||||
http.put('/api/admin/collab-features', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
|
||||
);
|
||||
renderAdmin();
|
||||
await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument());
|
||||
await openSection('Addons');
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('chat-state')).toHaveTextContent('true'));
|
||||
fireEvent.click(screen.getByRole('button', { name: 'toggle chat' }));
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('chat-state')).toHaveTextContent('true'));
|
||||
});
|
||||
|
||||
it('FE-MOB-ADMIN-017: the stats grid falls back to zero files', async () => {
|
||||
server.use(
|
||||
http.get('/api/admin/stats', () =>
|
||||
HttpResponse.json({ totalUsers: 3, totalTrips: 7, totalPlaces: 11 }),
|
||||
),
|
||||
);
|
||||
renderAdmin();
|
||||
|
||||
await screen.findByText('11');
|
||||
expect(screen.getByText('3')).toBeInTheDocument();
|
||||
expect(screen.getByText('7')).toBeInTheDocument();
|
||||
expect(screen.getByText('0')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,482 @@
|
||||
// FE-MOB-AADD-001 to FE-MOB-AADD-023
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { delay, http, HttpResponse } from 'msw';
|
||||
import { render, screen, waitFor, within } from '../../../helpers/render';
|
||||
import { server } from '../../../helpers/msw/server';
|
||||
import { resetAllStores, seedStore } from '../../../helpers/store';
|
||||
import { buildSettings } from '../../../helpers/factories';
|
||||
import { useSettingsStore } from '../../../../src/store/settingsStore';
|
||||
import { useAddonStore } from '../../../../src/store/addonStore';
|
||||
import { ToastContainer } from '../../../../src/components/shared/Toast';
|
||||
import MAdminAddonManager from '../../../../src/mobile/screens/admin/MAdminAddonManager';
|
||||
|
||||
interface AddonFixture {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
icon: string;
|
||||
type: string;
|
||||
enabled: boolean;
|
||||
config?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
function buildAddon(overrides: Partial<AddonFixture> = {}): AddonFixture {
|
||||
return {
|
||||
id: 'todo',
|
||||
name: 'Todo List',
|
||||
description: 'Track tasks',
|
||||
icon: 'ListChecks',
|
||||
type: 'trip',
|
||||
enabled: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function addonsRoute(addons: AddonFixture[]) {
|
||||
return http.get('/api/admin/addons', () => HttpResponse.json({ addons }));
|
||||
}
|
||||
|
||||
function llmAddon(config: Record<string, unknown> = {}): AddonFixture {
|
||||
return buildAddon({
|
||||
id: 'llm_parsing',
|
||||
name: 'AI Parsing',
|
||||
description: 'Extract bookings from files',
|
||||
icon: 'Sparkles',
|
||||
type: 'integration',
|
||||
enabled: true,
|
||||
config,
|
||||
});
|
||||
}
|
||||
|
||||
function modelsRoute(names: string[], seen?: (string | null)[]) {
|
||||
return http.get('/api/admin/llm/local/models', ({ request }) => {
|
||||
seen?.push(new URL(request.url).searchParams.get('baseUrl'));
|
||||
return HttpResponse.json({ models: names.map(name => ({ name, size: 1 })) });
|
||||
});
|
||||
}
|
||||
|
||||
let loadAddonsSpy: ReturnType<typeof vi.spyOn>;
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
seedStore(useSettingsStore, { settings: buildSettings({ dark_mode: false }) });
|
||||
loadAddonsSpy = vi.spyOn(useAddonStore.getState(), 'loadAddons').mockResolvedValue(undefined);
|
||||
server.use(addonsRoute([]));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('MAdminAddonManager', () => {
|
||||
it('FE-MOB-AADD-001: shows the spinner while addons load', async () => {
|
||||
server.use(
|
||||
http.get('/api/admin/addons', async () => {
|
||||
await delay(60);
|
||||
return HttpResponse.json({ addons: [] });
|
||||
}),
|
||||
);
|
||||
render(<MAdminAddonManager />);
|
||||
|
||||
expect(document.querySelector('.animate-spin')).toBeInTheDocument();
|
||||
await screen.findByText('No addons available');
|
||||
expect(document.querySelector('.animate-spin')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-002: the header uses the light wordmark in light mode', async () => {
|
||||
render(<MAdminAddonManager />);
|
||||
|
||||
await screen.findByText('No addons available');
|
||||
expect(screen.getByText('Addons')).toBeInTheDocument();
|
||||
expect(screen.getByAltText('TREK')).toHaveAttribute('src', '/text-dark.svg');
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-003: dark mode and auto+prefers-dark swap the wordmark', async () => {
|
||||
seedStore(useSettingsStore, { settings: buildSettings({ dark_mode: 'dark' }) });
|
||||
const { unmount } = render(<MAdminAddonManager />);
|
||||
await screen.findByText('No addons available');
|
||||
expect(screen.getByAltText('TREK')).toHaveAttribute('src', '/text-light.svg');
|
||||
unmount();
|
||||
|
||||
const matchMedia = vi.fn().mockReturnValue({ matches: true, addEventListener: vi.fn(), removeEventListener: vi.fn() });
|
||||
vi.stubGlobal('matchMedia', matchMedia);
|
||||
seedStore(useSettingsStore, { settings: buildSettings({ dark_mode: 'auto' }) });
|
||||
render(<MAdminAddonManager />);
|
||||
await screen.findByText('No addons available');
|
||||
expect(screen.getByAltText('TREK')).toHaveAttribute('src', '/text-light.svg');
|
||||
expect(matchMedia).toHaveBeenCalledWith('(prefers-color-scheme: dark)');
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-004: a failing load toasts the addon error', async () => {
|
||||
server.use(http.get('/api/admin/addons', () => HttpResponse.error()));
|
||||
render(<><ToastContainer /><MAdminAddonManager /></>);
|
||||
|
||||
await screen.findByText('Failed to update addon');
|
||||
expect(screen.getByText('No addons available')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-005: trip addons render with the section band, catalog label and type badge', async () => {
|
||||
server.use(addonsRoute([buildAddon({ id: 'packing', name: 'Packing', enabled: true })]));
|
||||
render(<MAdminAddonManager />);
|
||||
|
||||
await screen.findByText('Lists');
|
||||
expect(screen.getByText('Trip — Available as a tab within each trip')).toBeInTheDocument();
|
||||
expect(screen.getByText('Packing lists and to-do tasks for your trips')).toBeInTheDocument();
|
||||
expect(screen.getByText('Trip')).toBeInTheDocument();
|
||||
expect(screen.getByRole('switch', { name: 'Lists' })).toHaveAttribute('aria-checked', 'true');
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-006: an addon without a catalog entry falls back to the API name', async () => {
|
||||
server.use(addonsRoute([buildAddon({ id: 'mystery', name: 'Mystery Addon', description: 'No catalog key', icon: 'NoSuchIcon' })]));
|
||||
render(<MAdminAddonManager />);
|
||||
|
||||
await screen.findByText('Mystery Addon');
|
||||
expect(screen.getByText('No catalog key')).toBeInTheDocument();
|
||||
expect(screen.getByRole('switch', { name: 'Mystery Addon' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-007: photo-flavoured trip addons are hidden from the trip section', async () => {
|
||||
server.use(
|
||||
addonsRoute([
|
||||
buildAddon({ id: 'photos', name: 'Memories', icon: 'Image' }),
|
||||
buildAddon({ id: 'gallery', name: 'Trip Photos', icon: 'Puzzle', description: 'Share your photo stream' }),
|
||||
buildAddon({ id: 'todo', name: 'Todo List' }),
|
||||
]),
|
||||
);
|
||||
render(<MAdminAddonManager />);
|
||||
|
||||
await screen.findByText('Todo List');
|
||||
expect(screen.queryByText('Memories')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Trip Photos')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-008: toggling an addon persists it, refreshes the store and toasts', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: unknown = null;
|
||||
server.use(
|
||||
addonsRoute([buildAddon({ id: 'todo', enabled: false })]),
|
||||
http.put('/api/admin/addons/todo', async ({ request }) => {
|
||||
body = await request.json();
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
render(<><ToastContainer /><MAdminAddonManager /></>);
|
||||
await screen.findByText('Todo List');
|
||||
|
||||
const toggle = screen.getByRole('switch', { name: 'Todo List' });
|
||||
expect(toggle).toHaveAttribute('aria-checked', 'false');
|
||||
await user.click(toggle);
|
||||
|
||||
await waitFor(() => expect(body).toEqual({ enabled: true }));
|
||||
expect(toggle).toHaveAttribute('aria-checked', 'true');
|
||||
expect(loadAddonsSpy).toHaveBeenCalled();
|
||||
await screen.findByText('Addon updated');
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-009: a failing toggle rolls the switch back', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
addonsRoute([buildAddon({ id: 'todo', enabled: true })]),
|
||||
http.put('/api/admin/addons/todo', () => HttpResponse.error()),
|
||||
);
|
||||
render(<><ToastContainer /><MAdminAddonManager /></>);
|
||||
await screen.findByText('Todo List');
|
||||
|
||||
const toggle = screen.getByRole('switch', { name: 'Todo List' });
|
||||
await user.click(toggle);
|
||||
|
||||
await screen.findByText('Failed to update addon');
|
||||
await waitFor(() => expect(toggle).toHaveAttribute('aria-checked', 'true'));
|
||||
expect(loadAddonsSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-010: bag tracking shows under an enabled packing addon and reports clicks', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onToggleBagTracking = vi.fn();
|
||||
server.use(addonsRoute([buildAddon({ id: 'packing', enabled: true })]));
|
||||
render(<MAdminAddonManager bagTrackingEnabled={false} onToggleBagTracking={onToggleBagTracking} />);
|
||||
|
||||
await screen.findByText('Bag Tracking');
|
||||
expect(screen.getByText('Enable weight and bag assignment for packing items')).toBeInTheDocument();
|
||||
const bagToggle = screen.getByRole('switch', { name: 'Bag Tracking' });
|
||||
expect(bagToggle).toHaveAttribute('aria-checked', 'false');
|
||||
|
||||
await user.click(bagToggle);
|
||||
expect(onToggleBagTracking).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-011: bag tracking stays hidden when packing is off or the handler is missing', async () => {
|
||||
server.use(addonsRoute([buildAddon({ id: 'packing', enabled: false })]));
|
||||
const { unmount } = render(<MAdminAddonManager bagTrackingEnabled onToggleBagTracking={vi.fn()} />);
|
||||
await screen.findByText('Lists');
|
||||
expect(screen.queryByText('Bag Tracking')).not.toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
server.use(addonsRoute([buildAddon({ id: 'packing', enabled: true })]));
|
||||
render(<MAdminAddonManager bagTrackingEnabled />);
|
||||
await screen.findByText('Lists');
|
||||
expect(screen.queryByText('Bag Tracking')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-012: the collab sub-features render and report the toggled key', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onToggleCollabFeature = vi.fn();
|
||||
server.use(addonsRoute([buildAddon({ id: 'collab', name: 'Collab', enabled: true })]));
|
||||
render(
|
||||
<MAdminAddonManager
|
||||
collabFeatures={{ chat: true, notes: false, polls: false, whatsnext: true }}
|
||||
onToggleCollabFeature={onToggleCollabFeature}
|
||||
/>,
|
||||
);
|
||||
|
||||
await screen.findByText('Chat');
|
||||
expect(screen.getByText('Notes')).toBeInTheDocument();
|
||||
expect(screen.getByText('Polls')).toBeInTheDocument();
|
||||
expect(screen.getByText("What's Next")).toBeInTheDocument();
|
||||
expect(screen.getByRole('switch', { name: 'Chat' })).toHaveAttribute('aria-checked', 'true');
|
||||
expect(screen.getByRole('switch', { name: 'Notes' })).toHaveAttribute('aria-checked', 'false');
|
||||
|
||||
await user.click(screen.getByRole('switch', { name: 'Polls' }));
|
||||
expect(onToggleCollabFeature).toHaveBeenCalledWith('polls');
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-013: collab sub-features stay hidden without the handler props', async () => {
|
||||
server.use(addonsRoute([buildAddon({ id: 'collab', name: 'Collab', enabled: true })]));
|
||||
render(<MAdminAddonManager />);
|
||||
|
||||
await screen.findByText('Collab');
|
||||
expect(screen.queryByText('Polls')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-014: photo providers render as sub-rows under the journey addon', async () => {
|
||||
server.use(
|
||||
addonsRoute([
|
||||
buildAddon({ id: 'journey', name: 'Journey', type: 'global', icon: 'Compass', enabled: true }),
|
||||
buildAddon({ id: 'immich', name: 'Immich', description: 'Self-hosted photos', type: 'photo_provider', enabled: true }),
|
||||
buildAddon({ id: 'synologyphotos', name: 'Synology Photos', description: 'NAS photos', type: 'photo_provider', enabled: false }),
|
||||
buildAddon({ id: 'unsplash', name: 'Unsplash', description: 'Stock photos', type: 'photo_provider', enabled: false }),
|
||||
]),
|
||||
);
|
||||
render(<MAdminAddonManager />);
|
||||
|
||||
await screen.findByText('Immich');
|
||||
expect(screen.getByText('Global — Available as a standalone section in the main navigation')).toBeInTheDocument();
|
||||
expect(screen.getByText('Synology Photos')).toBeInTheDocument();
|
||||
expect(screen.getByText('Unsplash')).toBeInTheDocument();
|
||||
expect(screen.getByRole('switch', { name: 'Immich' })).toHaveAttribute('aria-checked', 'true');
|
||||
// Journey + three providers, and providers are not shown as top-level rows.
|
||||
expect(screen.getAllByRole('switch')).toHaveLength(4);
|
||||
expect(screen.queryByText('Global')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-015: toggling a provider persists it and rolls back on failure', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: unknown = null;
|
||||
server.use(
|
||||
addonsRoute([
|
||||
buildAddon({ id: 'journey', name: 'Journey', type: 'global', icon: 'Compass', enabled: true }),
|
||||
buildAddon({ id: 'immich', name: 'Immich', description: 'Self-hosted photos', type: 'photo_provider', enabled: false }),
|
||||
buildAddon({ id: 'unsplash', name: 'Unsplash', description: 'Stock photos', type: 'photo_provider', enabled: false }),
|
||||
]),
|
||||
http.put('/api/admin/addons/immich', async ({ request }) => {
|
||||
body = await request.json();
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
http.put('/api/admin/addons/unsplash', () => HttpResponse.error()),
|
||||
);
|
||||
render(<><ToastContainer /><MAdminAddonManager /></>);
|
||||
await screen.findByText('Immich');
|
||||
|
||||
await user.click(screen.getByRole('switch', { name: 'Immich' }));
|
||||
await waitFor(() => expect(body).toEqual({ enabled: true }));
|
||||
expect(screen.getByRole('switch', { name: 'Immich' })).toHaveAttribute('aria-checked', 'true');
|
||||
await screen.findByText('Addon updated');
|
||||
|
||||
await user.click(screen.getByRole('switch', { name: 'Unsplash' }));
|
||||
await screen.findByText('Failed to update addon');
|
||||
await waitFor(() => expect(screen.getByRole('switch', { name: 'Unsplash' })).toHaveAttribute('aria-checked', 'false'));
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-016: a disabled AI-parsing addon renders the integration row without its config', async () => {
|
||||
server.use(addonsRoute([llmAddon({ provider: 'local' })].map(a => ({ ...a, enabled: false }))));
|
||||
render(<MAdminAddonManager />);
|
||||
|
||||
await screen.findByText('AI Parsing');
|
||||
expect(screen.getByText('Integration — Backend services and API integrations with no dedicated page')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Connection')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-017: the local provider lists installed models and selecting a chip fills the model field', async () => {
|
||||
const user = userEvent.setup();
|
||||
const urls: (string | null)[] = [];
|
||||
server.use(addonsRoute([llmAddon({ provider: 'local' })]), modelsRoute(['qwen3:8b', 'llama3:8b'], urls));
|
||||
render(<MAdminAddonManager />);
|
||||
|
||||
await screen.findByText('Installed on the server');
|
||||
await screen.findByRole('button', { name: 'llama3:8b' });
|
||||
expect(urls[0]).toBe('http://localhost:11434/v1');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'llama3:8b' }));
|
||||
expect(screen.getByPlaceholderText('select or pull below')).toHaveValue('llama3:8b');
|
||||
|
||||
// qwen3:8b is installed, so the recommended row offers "Use" instead of "Pull".
|
||||
await user.click(screen.getByRole('button', { name: 'Use' }));
|
||||
expect(screen.getByPlaceholderText('select or pull below')).toHaveValue('qwen3:8b');
|
||||
expect(screen.getByRole('button', { name: 'Selected' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-018: an unreachable Ollama shows the error, Refresh retries', async () => {
|
||||
const user = userEvent.setup();
|
||||
let calls = 0;
|
||||
server.use(
|
||||
addonsRoute([llmAddon({ provider: 'local' })]),
|
||||
http.get('/api/admin/llm/local/models', () => {
|
||||
calls += 1;
|
||||
return calls === 1
|
||||
? HttpResponse.json({ error: 'down' }, { status: 500 })
|
||||
: HttpResponse.json({ models: [] });
|
||||
}),
|
||||
);
|
||||
render(<MAdminAddonManager />);
|
||||
|
||||
await screen.findByText(/Request failed with status code 500/);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Refresh' }));
|
||||
await screen.findByText('No models installed yet — pull one below.');
|
||||
expect(calls).toBe(2);
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-019: the base URL is used for model lookups on blur', async () => {
|
||||
const user = userEvent.setup();
|
||||
const urls: (string | null)[] = [];
|
||||
server.use(addonsRoute([llmAddon({ provider: 'local' })]), modelsRoute([], urls));
|
||||
render(<MAdminAddonManager />);
|
||||
|
||||
await screen.findByText('Installed on the server');
|
||||
const baseUrl = screen.getByPlaceholderText('http://localhost:11434/v1');
|
||||
await user.type(baseUrl, 'http://ollama.lan:11434/v1');
|
||||
await user.tab();
|
||||
|
||||
await waitFor(() => expect(urls).toContain('http://ollama.lan:11434/v1'));
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-020: switching providers swaps the base URL field and the model hint', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(addonsRoute([llmAddon({ provider: 'local', apiKey: '••••••••' })]), modelsRoute([]));
|
||||
render(<MAdminAddonManager />);
|
||||
|
||||
await screen.findByText('Installed on the server');
|
||||
expect(screen.getByPlaceholderText('••••••••')).toBeInTheDocument();
|
||||
|
||||
await user.type(screen.getByPlaceholderText('select or pull below'), 'mistral:7b');
|
||||
expect(screen.getByDisplayValue('mistral:7b')).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'OpenAI' }));
|
||||
expect(screen.getByPlaceholderText('https://api.openai.com/v1')).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText('gpt-4o')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Installed on the server')).not.toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Anthropic' }));
|
||||
expect(screen.queryByPlaceholderText('https://api.openai.com/v1')).not.toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText('claude-opus-4-8')).toBeInTheDocument();
|
||||
expect(screen.getByText(/Anthropic reads PDFs/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-021: pulling a model streams progress, then selects it', async () => {
|
||||
const user = userEvent.setup();
|
||||
let pulled: unknown = null;
|
||||
let modelCalls = 0;
|
||||
server.use(
|
||||
addonsRoute([llmAddon({ provider: 'local' })]),
|
||||
http.get('/api/admin/llm/local/models', () => {
|
||||
modelCalls += 1;
|
||||
return HttpResponse.json({ models: modelCalls === 1 ? [] : [{ name: 'qwen3:8b', size: 1 }] });
|
||||
}),
|
||||
http.post('/api/admin/llm/local/pull', async ({ request }) => {
|
||||
pulled = await request.json();
|
||||
await delay(150);
|
||||
return new HttpResponse(
|
||||
'{"status":"pulling manifest"}\n{"status":"downloading","total":100,"completed":40}\nnot-json\n',
|
||||
{ headers: { 'Content-Type': 'application/x-ndjson' } },
|
||||
);
|
||||
}),
|
||||
);
|
||||
render(<><ToastContainer /><MAdminAddonManager /></>);
|
||||
|
||||
await screen.findByText('No models installed yet — pull one below.');
|
||||
await user.click(screen.getByRole('button', { name: 'Pull' }));
|
||||
|
||||
// While the request is in flight the row shows the busy label and status line.
|
||||
await screen.findByText('Pulling…');
|
||||
expect(screen.getByText('starting…')).toBeInTheDocument();
|
||||
|
||||
await screen.findByText('Model pulled');
|
||||
expect(pulled).toEqual({ baseUrl: 'http://localhost:11434/v1', model: 'qwen3:8b' });
|
||||
expect(screen.getByPlaceholderText('select or pull below')).toHaveValue('qwen3:8b');
|
||||
// Reloaded models now contain the pulled one, so the row switches to "Selected".
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Selected' })).toBeDisabled());
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-022: a failing pull surfaces the server error', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
addonsRoute([llmAddon({ provider: 'local' })]),
|
||||
modelsRoute([]),
|
||||
http.post('/api/admin/llm/local/pull', () => HttpResponse.json({ error: 'no disk space' }, { status: 500 })),
|
||||
);
|
||||
render(<><ToastContainer /><MAdminAddonManager /></>);
|
||||
|
||||
await screen.findByText('No models installed yet — pull one below.');
|
||||
await user.click(screen.getByRole('button', { name: 'Pull' }));
|
||||
|
||||
await screen.findByText('no disk space');
|
||||
expect(screen.getByRole('button', { name: 'Pull' })).toBeEnabled();
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-023: saving posts the whole config and reports both outcomes', async () => {
|
||||
const user = userEvent.setup();
|
||||
const bodies: unknown[] = [];
|
||||
server.use(
|
||||
addonsRoute([llmAddon({ provider: 'openai', model: 'gpt-4o', baseUrl: 'https://api.openai.com/v1', apiKey: '••••••••', multimodal: true })]),
|
||||
http.put('/api/admin/addons/llm_parsing', async ({ request }) => {
|
||||
bodies.push(await request.json());
|
||||
return bodies.length === 1 ? HttpResponse.json({ success: true }) : HttpResponse.error();
|
||||
}),
|
||||
);
|
||||
render(<><ToastContainer /><MAdminAddonManager /></>);
|
||||
|
||||
const save = await screen.findByRole('button', { name: 'Save' });
|
||||
await user.click(save);
|
||||
|
||||
await screen.findByText('Saved');
|
||||
expect(bodies[0]).toEqual({
|
||||
config: {
|
||||
provider: 'openai',
|
||||
model: 'gpt-4o',
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
apiKey: '••••••••',
|
||||
multimodal: true,
|
||||
},
|
||||
});
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
await screen.findByText('Failed to save');
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-024: the API key field can be revealed', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(addonsRoute([llmAddon({ provider: 'anthropic', apiKey: 'sk-secret' })]));
|
||||
render(<MAdminAddonManager />);
|
||||
|
||||
const field = await screen.findByDisplayValue('sk-secret');
|
||||
expect(field).toHaveAttribute('type', 'password');
|
||||
|
||||
await user.click(within(field.parentElement as HTMLElement).getByRole('button', { name: 'Show or hide' }));
|
||||
expect(screen.getByDisplayValue('sk-secret')).toHaveAttribute('type', 'text');
|
||||
|
||||
await user.type(screen.getByDisplayValue('sk-secret'), '-rotated');
|
||||
expect(screen.getByDisplayValue('sk-secret-rotated')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,217 @@
|
||||
// FE-MOB-AUDIT-001 to FE-MOB-AUDIT-012
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { render, screen, waitFor } from '../../../helpers/render';
|
||||
import { server } from '../../../helpers/msw/server';
|
||||
import { resetAllStores } from '../../../helpers/store';
|
||||
import MAdminAuditLogPanel from '../../../../src/mobile/screens/admin/MAdminAuditLogPanel';
|
||||
|
||||
const ENTRY_1 = {
|
||||
id: 1,
|
||||
created_at: '2025-06-01T10:30:00Z',
|
||||
user_id: 5,
|
||||
username: 'alice',
|
||||
user_email: 'alice@example.com',
|
||||
action: 'trip.create',
|
||||
resource: '/trips/42',
|
||||
details: { title: 'Test' },
|
||||
ip: '127.0.0.1',
|
||||
};
|
||||
|
||||
const ENTRY_2 = {
|
||||
id: 2,
|
||||
created_at: '2025-06-02T11:00:00Z',
|
||||
user_id: 6,
|
||||
username: 'bob',
|
||||
user_email: 'bob@example.com',
|
||||
action: 'trip.delete',
|
||||
resource: null,
|
||||
details: null,
|
||||
ip: null,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
describe('MAdminAuditLogPanel', () => {
|
||||
it('FE-MOB-AUDIT-001: header, subtitle and the loading placeholder render on mount', () => {
|
||||
server.use(
|
||||
http.get('/api/admin/audit-log', async () => {
|
||||
await new Promise(() => {});
|
||||
return HttpResponse.json({ entries: [], total: 0 });
|
||||
}),
|
||||
);
|
||||
render(<MAdminAuditLogPanel serverTimezone="UTC" />);
|
||||
|
||||
expect(screen.getByText('Audit')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText('Security-sensitive and administration events (backups, users, MFA, settings).'),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText('Loading...')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Refresh' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-MOB-AUDIT-002: empty state and a zeroed counter when there is nothing to show', async () => {
|
||||
server.use(http.get('/api/admin/audit-log', () => HttpResponse.json({ entries: [], total: 0 })));
|
||||
render(<MAdminAuditLogPanel serverTimezone="UTC" />);
|
||||
|
||||
await screen.findByText('No audit entries yet.');
|
||||
expect(screen.getByText('0 loaded · 0 total')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Load more')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AUDIT-003: an entry card shows action, user, resource, ip and details', async () => {
|
||||
server.use(http.get('/api/admin/audit-log', () => HttpResponse.json({ entries: [ENTRY_1], total: 1 })));
|
||||
render(<MAdminAuditLogPanel serverTimezone="UTC" />);
|
||||
|
||||
await screen.findByText('trip.create');
|
||||
expect(screen.getByText('User')).toBeInTheDocument();
|
||||
expect(screen.getByText('Resource')).toBeInTheDocument();
|
||||
expect(screen.getByText('IP')).toBeInTheDocument();
|
||||
expect(screen.getByText('Details')).toBeInTheDocument();
|
||||
expect(screen.getByText('alice')).toBeInTheDocument();
|
||||
expect(screen.getByText('/trips/42')).toBeInTheDocument();
|
||||
expect(screen.getByText('127.0.0.1')).toBeInTheDocument();
|
||||
expect(screen.getByText('{"title":"Test"}')).toBeInTheDocument();
|
||||
expect(screen.getByText('1 loaded · 1 total')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AUDIT-004: the timestamp is rendered in the server timezone', async () => {
|
||||
server.use(http.get('/api/admin/audit-log', () => HttpResponse.json({ entries: [ENTRY_1], total: 1 })));
|
||||
render(<MAdminAuditLogPanel serverTimezone="UTC" />);
|
||||
|
||||
await screen.findByText('trip.create');
|
||||
expect(screen.getByText('6/1/25, 10:30:00 AM')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AUDIT-005: timestamps without a Z suffix are treated as UTC', async () => {
|
||||
const naive = { ...ENTRY_1, created_at: '2025-06-01T10:30:00' };
|
||||
server.use(http.get('/api/admin/audit-log', () => HttpResponse.json({ entries: [naive], total: 1 })));
|
||||
render(<MAdminAuditLogPanel serverTimezone="UTC" />);
|
||||
|
||||
await screen.findByText('trip.create');
|
||||
expect(screen.getByText('6/1/25, 10:30:00 AM')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AUDIT-006: an unusable timezone falls back to the raw timestamp', async () => {
|
||||
server.use(http.get('/api/admin/audit-log', () => HttpResponse.json({ entries: [ENTRY_1], total: 1 })));
|
||||
render(<MAdminAuditLogPanel serverTimezone="Not/AZone" />);
|
||||
|
||||
await screen.findByText('trip.create');
|
||||
expect(screen.getByText('2025-06-01T10:30:00Z')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AUDIT-007: the user label falls back through email, id and dash', async () => {
|
||||
const entries = [
|
||||
{ ...ENTRY_1, id: 10, action: 'a.username' },
|
||||
{ ...ENTRY_1, id: 11, username: null, action: 'a.email' },
|
||||
{ ...ENTRY_1, id: 12, username: null, user_email: null, user_id: 7, action: 'a.id' },
|
||||
{ ...ENTRY_1, id: 13, username: null, user_email: null, user_id: null, action: 'a.none' },
|
||||
];
|
||||
server.use(http.get('/api/admin/audit-log', () => HttpResponse.json({ entries, total: 4 })));
|
||||
render(<MAdminAuditLogPanel serverTimezone="UTC" />);
|
||||
|
||||
await screen.findByText('a.username');
|
||||
expect(screen.getByText('alice')).toBeInTheDocument();
|
||||
expect(screen.getByText('alice@example.com')).toBeInTheDocument();
|
||||
expect(screen.getByText('#7')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('—')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-MOB-AUDIT-008: null resource, ip and details render as a dash', async () => {
|
||||
const emptyDetails = { ...ENTRY_1, id: 21, action: 'a.emptyobj', details: {} };
|
||||
server.use(
|
||||
http.get('/api/admin/audit-log', () => HttpResponse.json({ entries: [ENTRY_2, emptyDetails], total: 2 })),
|
||||
);
|
||||
render(<MAdminAuditLogPanel serverTimezone="UTC" />);
|
||||
|
||||
await screen.findByText('trip.delete');
|
||||
// ENTRY_2 contributes three dashes, the empty details object a fourth
|
||||
expect(screen.getAllByText('—')).toHaveLength(4);
|
||||
});
|
||||
|
||||
it('FE-MOB-AUDIT-009: Load more appends the next page and disappears when complete', async () => {
|
||||
const user = userEvent.setup();
|
||||
const offsets: string[] = [];
|
||||
server.use(
|
||||
http.get('/api/admin/audit-log', ({ request }) => {
|
||||
const offset = new URL(request.url).searchParams.get('offset') ?? '';
|
||||
offsets.push(offset);
|
||||
return offset === '0'
|
||||
? HttpResponse.json({ entries: [ENTRY_1], total: 2 })
|
||||
: HttpResponse.json({ entries: [ENTRY_2], total: 2 });
|
||||
}),
|
||||
);
|
||||
render(<MAdminAuditLogPanel serverTimezone="UTC" />);
|
||||
|
||||
await screen.findByText('trip.create');
|
||||
await user.click(screen.getByRole('button', { name: 'Load more' }));
|
||||
|
||||
await screen.findByText('trip.delete');
|
||||
expect(screen.getByText('trip.create')).toBeInTheDocument();
|
||||
expect(screen.getByText('2 loaded · 2 total')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Load more' })).not.toBeInTheDocument();
|
||||
expect(offsets).toEqual(['0', '100']);
|
||||
});
|
||||
|
||||
it('FE-MOB-AUDIT-010: a failing Load more keeps the entries already loaded', async () => {
|
||||
const user = userEvent.setup();
|
||||
let call = 0;
|
||||
server.use(
|
||||
http.get('/api/admin/audit-log', () => {
|
||||
call += 1;
|
||||
return call === 1
|
||||
? HttpResponse.json({ entries: [ENTRY_1], total: 5 })
|
||||
: HttpResponse.json({ error: 'boom' }, { status: 500 });
|
||||
}),
|
||||
);
|
||||
render(<MAdminAuditLogPanel serverTimezone="UTC" />);
|
||||
|
||||
await screen.findByText('trip.create');
|
||||
await user.click(screen.getByRole('button', { name: 'Load more' }));
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Load more' })).not.toBeDisabled());
|
||||
expect(screen.getByText('trip.create')).toBeInTheDocument();
|
||||
expect(screen.getByText('1 loaded · 5 total')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AUDIT-011: Refresh throws away the appended pages', async () => {
|
||||
const user = userEvent.setup();
|
||||
let call = 0;
|
||||
server.use(
|
||||
http.get('/api/admin/audit-log', () => {
|
||||
call += 1;
|
||||
if (call === 1) return HttpResponse.json({ entries: [ENTRY_1], total: 2 });
|
||||
if (call === 2) return HttpResponse.json({ entries: [ENTRY_2], total: 2 });
|
||||
return HttpResponse.json({ entries: [{ ...ENTRY_1, id: 99, action: 'after.refresh' }], total: 1 });
|
||||
}),
|
||||
);
|
||||
render(<MAdminAuditLogPanel serverTimezone="UTC" />);
|
||||
|
||||
await screen.findByText('trip.create');
|
||||
await user.click(screen.getByRole('button', { name: 'Load more' }));
|
||||
await screen.findByText('trip.delete');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Refresh' }));
|
||||
|
||||
await screen.findByText('after.refresh');
|
||||
expect(screen.queryByText('trip.create')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('trip.delete')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('1 loaded · 1 total')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AUDIT-012: a failing first page falls back to the empty state', async () => {
|
||||
server.use(http.get('/api/admin/audit-log', () => HttpResponse.json({ error: 'boom' }, { status: 500 })));
|
||||
render(<MAdminAuditLogPanel />);
|
||||
|
||||
await screen.findByText('No audit entries yet.');
|
||||
expect(screen.getByText('0 loaded · 0 total')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,455 @@
|
||||
// FE-MOB-MBKP-001 to FE-MOB-MBKP-026
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { render, screen, waitFor, within, fireEvent } from '../../../helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../helpers/msw/server';
|
||||
import { resetAllStores, seedStore } from '../../../helpers/store';
|
||||
import { buildSettings } from '../../../helpers/factories';
|
||||
import { useSettingsStore } from '../../../../src/store/settingsStore';
|
||||
import { ToastContainer } from '../../../../src/components/shared/Toast';
|
||||
import MAdminBackupPanel from '../../../../src/mobile/screens/admin/MAdminBackupPanel';
|
||||
|
||||
const manualBackup = { filename: 'backup-2025-01-15.zip', created_at: '2025-01-15T10:00:00Z', size: 2_048_000 };
|
||||
const autoBackup = { filename: 'auto-backup-2025-02-01.zip', created_at: '2025-02-01T02:00:00Z', size: 512_000 };
|
||||
|
||||
const DEFAULT_AUTO = { enabled: false, interval: 'daily', keep_days: 7, hour: 2, day_of_week: 0, day_of_month: 1 };
|
||||
|
||||
function autoSettingsHandler(settings: Record<string, unknown> = DEFAULT_AUTO, timezone: string | null = 'UTC') {
|
||||
return http.get('/api/backup/auto-settings', () =>
|
||||
HttpResponse.json(timezone === null ? { settings } : { settings, timezone }),
|
||||
);
|
||||
}
|
||||
|
||||
function listHandler(backups: unknown[]) {
|
||||
return http.get('/api/backup/list', () => HttpResponse.json({ backups }));
|
||||
}
|
||||
|
||||
function withToast() {
|
||||
return render(<><ToastContainer /><MAdminBackupPanel /></>);
|
||||
}
|
||||
|
||||
function fileInput(): HTMLInputElement {
|
||||
return document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
}
|
||||
|
||||
/** Stub window.location so the post-restore reload cannot navigate jsdom. */
|
||||
function stubReload() {
|
||||
const reload = vi.fn();
|
||||
vi.stubGlobal('location', { ...window.location, reload });
|
||||
return reload;
|
||||
}
|
||||
|
||||
describe('MAdminBackupPanel', () => {
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
seedStore(useSettingsStore, { settings: buildSettings({ time_format: '24h' }) });
|
||||
server.use(listHandler([manualBackup]), autoSettingsHandler());
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-001: renders the backup card with filename and formatted size', async () => {
|
||||
render(<MAdminBackupPanel />);
|
||||
|
||||
expect(await screen.findByText('backup-2025-01-15.zip')).toBeInTheDocument();
|
||||
expect(screen.getByText('Data Backup')).toBeInTheDocument();
|
||||
expect(screen.getByText('Database and all uploaded files')).toBeInTheDocument();
|
||||
expect(screen.getByText('2.0 MB')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Auto')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-002: sub-megabyte sizes are shown in KB and missing metadata as a dash', async () => {
|
||||
server.use(listHandler([
|
||||
{ filename: 'small.zip', created_at: '2025-03-01T08:00:00Z', size: 4096 },
|
||||
{ filename: 'unknown.zip', created_at: null, size: 0 },
|
||||
]));
|
||||
render(<MAdminBackupPanel />);
|
||||
|
||||
expect(await screen.findByText('4.0 KB')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('-')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-003: files named auto-backup-* get the Auto badge', async () => {
|
||||
server.use(listHandler([autoBackup]));
|
||||
render(<MAdminBackupPanel />);
|
||||
|
||||
expect(await screen.findByText('auto-backup-2025-02-01.zip')).toBeInTheDocument();
|
||||
expect(screen.getByText('Auto')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-004: shows the loading row first and the empty state when nothing is stored', async () => {
|
||||
server.use(listHandler([]));
|
||||
render(<MAdminBackupPanel />);
|
||||
|
||||
expect(screen.getByText('Loading...')).toBeInTheDocument();
|
||||
|
||||
expect(await screen.findByText('No backups yet')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Create first backup' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-005: a failing list request shows the load error toast', async () => {
|
||||
server.use(http.get('/api/backup/list', () => HttpResponse.json({ error: 'boom' }, { status: 500 })));
|
||||
withToast();
|
||||
|
||||
expect(await screen.findByText('Failed to load backups')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-006: the refresh button re-reads the list', async () => {
|
||||
const user = userEvent.setup();
|
||||
let calls = 0;
|
||||
server.use(http.get('/api/backup/list', () => {
|
||||
calls += 1;
|
||||
return HttpResponse.json({ backups: calls === 1 ? [manualBackup] : [manualBackup, autoBackup] });
|
||||
}));
|
||||
render(<MAdminBackupPanel />);
|
||||
await screen.findByText('backup-2025-01-15.zip');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Refresh' }));
|
||||
|
||||
expect(await screen.findByText('auto-backup-2025-02-01.zip')).toBeInTheDocument();
|
||||
expect(calls).toBe(2);
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-007: creating a backup posts, toasts and reloads the list', async () => {
|
||||
const user = userEvent.setup();
|
||||
let created = false;
|
||||
server.use(
|
||||
http.post('/api/backup/create', () => { created = true; return HttpResponse.json({ success: true }); }),
|
||||
http.get('/api/backup/list', () => HttpResponse.json({ backups: created ? [manualBackup, autoBackup] : [manualBackup] })),
|
||||
);
|
||||
withToast();
|
||||
await screen.findByText('backup-2025-01-15.zip');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Create Backup' }));
|
||||
|
||||
expect(await screen.findByText('Backup created successfully')).toBeInTheDocument();
|
||||
expect(await screen.findByText('auto-backup-2025-02-01.zip')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-008: a failing create shows the create error toast', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(http.post('/api/backup/create', () => HttpResponse.json({ error: 'disk full' }, { status: 500 })));
|
||||
withToast();
|
||||
await screen.findByText('backup-2025-01-15.zip');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Create Backup' }));
|
||||
|
||||
expect(await screen.findByText('Failed to create backup')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-009: the empty-state shortcut also creates a backup', async () => {
|
||||
const user = userEvent.setup();
|
||||
let created = false;
|
||||
server.use(
|
||||
listHandler([]),
|
||||
http.post('/api/backup/create', () => { created = true; return HttpResponse.json({ success: true }); }),
|
||||
);
|
||||
withToast();
|
||||
await screen.findByText('No backups yet');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Create first backup' }));
|
||||
|
||||
await waitFor(() => expect(created).toBe(true));
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-010: a failing download shows the download error toast', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(http.get('/api/backup/download/:filename', () => new HttpResponse(null, { status: 500 })));
|
||||
withToast();
|
||||
await screen.findByText('backup-2025-01-15.zip');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Download' }));
|
||||
|
||||
expect(await screen.findByText('Download failed')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-011: Restore opens the warning sheet and cancelling leaves the API untouched', async () => {
|
||||
const user = userEvent.setup();
|
||||
let restored = false;
|
||||
server.use(http.post('/api/backup/restore/:filename', () => { restored = true; return HttpResponse.json({ ok: true }); }));
|
||||
render(<MAdminBackupPanel />);
|
||||
await screen.findByText('backup-2025-01-15.zip');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Restore' }));
|
||||
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
expect(within(dialog).getByText('Restore Backup?')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('backup-2025-01-15.zip')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText(/Tip: Create a backup of the current state/)).toBeInTheDocument();
|
||||
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Cancel' }));
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
|
||||
expect(restored).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-012: confirming a restore calls the API and reloads the page after 1.5s', async () => {
|
||||
const user = userEvent.setup();
|
||||
let restoredFile = '';
|
||||
server.use(http.post('/api/backup/restore/:filename', ({ params }) => {
|
||||
restoredFile = String(params.filename);
|
||||
return HttpResponse.json({ success: true });
|
||||
}));
|
||||
withToast();
|
||||
await screen.findByText('backup-2025-01-15.zip');
|
||||
|
||||
const reload = stubReload();
|
||||
await user.click(screen.getByRole('button', { name: 'Restore' }));
|
||||
await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Yes, restore' }));
|
||||
|
||||
expect(await screen.findByText('Backup restored. Page will reload…')).toBeInTheDocument();
|
||||
expect(restoredFile).toBe('backup-2025-01-15.zip');
|
||||
await waitFor(() => expect(reload).toHaveBeenCalled(), { timeout: 4000 });
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-013: a failing restore surfaces the server error and clears the busy state', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(http.post('/api/backup/restore/:filename', () =>
|
||||
HttpResponse.json({ error: 'Archive is corrupt' }, { status: 400 }),
|
||||
));
|
||||
withToast();
|
||||
await screen.findByText('backup-2025-01-15.zip');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Restore' }));
|
||||
await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Yes, restore' }));
|
||||
|
||||
expect(await screen.findByText('Archive is corrupt')).toBeInTheDocument();
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Restore' })).toBeEnabled());
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-014: picking a file opens the upload confirmation with the file name', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<MAdminBackupPanel />);
|
||||
await screen.findByText('backup-2025-01-15.zip');
|
||||
|
||||
// The visible button only forwards to the hidden picker; jsdom cannot open it
|
||||
const picker = vi.spyOn(fileInput(), 'click');
|
||||
await user.click(screen.getByRole('button', { name: 'Upload Backup' }));
|
||||
expect(picker).toHaveBeenCalled();
|
||||
|
||||
fireEvent.change(fileInput(), {
|
||||
target: { files: [new File(['zip'], 'restore-me.zip', { type: 'application/zip' })] },
|
||||
});
|
||||
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
expect(within(dialog).getByText('restore-me.zip')).toBeInTheDocument();
|
||||
// The picker is cleared so re-selecting the same file fires change again
|
||||
expect(fileInput().value).toBe('');
|
||||
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Cancel' }));
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-015: an empty file selection opens no sheet', async () => {
|
||||
render(<MAdminBackupPanel />);
|
||||
await screen.findByText('backup-2025-01-15.zip');
|
||||
|
||||
fireEvent.change(fileInput(), { target: { files: [] } });
|
||||
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-016: confirming an upload restore posts the archive and reloads', async () => {
|
||||
const user = userEvent.setup();
|
||||
let uploaded = false;
|
||||
server.use(http.post('/api/backup/upload-restore', () => { uploaded = true; return HttpResponse.json({ success: true }); }));
|
||||
withToast();
|
||||
await screen.findByText('backup-2025-01-15.zip');
|
||||
|
||||
const reload = stubReload();
|
||||
fireEvent.change(fileInput(), {
|
||||
target: { files: [new File(['zip'], 'restore-me.zip', { type: 'application/zip' })] },
|
||||
});
|
||||
await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Yes, restore' }));
|
||||
|
||||
expect(await screen.findByText('Backup restored. Page will reload…')).toBeInTheDocument();
|
||||
expect(uploaded).toBe(true);
|
||||
await waitFor(() => expect(reload).toHaveBeenCalled(), { timeout: 4000 });
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-017: a failing upload restore toasts the error and re-enables the upload button', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(http.post('/api/backup/upload-restore', () =>
|
||||
HttpResponse.json({ error: 'Not a TREK archive' }, { status: 400 }),
|
||||
));
|
||||
withToast();
|
||||
await screen.findByText('backup-2025-01-15.zip');
|
||||
|
||||
fireEvent.change(fileInput(), {
|
||||
target: { files: [new File(['zip'], 'broken.zip', { type: 'application/zip' })] },
|
||||
});
|
||||
await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Yes, restore' }));
|
||||
|
||||
expect(await screen.findByText('Not a TREK archive')).toBeInTheDocument();
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Upload Backup' })).toBeEnabled());
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-018: deleting asks for confirmation and drops the row on success', async () => {
|
||||
const user = userEvent.setup();
|
||||
let deletedFile = '';
|
||||
server.use(http.delete('/api/backup/:filename', ({ params }) => {
|
||||
deletedFile = String(params.filename);
|
||||
return HttpResponse.json({ success: true });
|
||||
}));
|
||||
withToast();
|
||||
await screen.findByText('backup-2025-01-15.zip');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Delete' }));
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
expect(within(dialog).getByText('Delete backup "backup-2025-01-15.zip"?')).toBeInTheDocument();
|
||||
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Cancel' }));
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
|
||||
expect(deletedFile).toBe('');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Delete' }));
|
||||
await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Delete' }));
|
||||
|
||||
expect(await screen.findByText('Backup deleted')).toBeInTheDocument();
|
||||
expect(deletedFile).toBe('backup-2025-01-15.zip');
|
||||
await waitFor(() => expect(screen.getByText('No backups yet')).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-019: a failing delete keeps the row and toasts the error', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(http.delete('/api/backup/:filename', () => HttpResponse.json({ error: 'locked' }, { status: 409 })));
|
||||
withToast();
|
||||
await screen.findByText('backup-2025-01-15.zip');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Delete' }));
|
||||
await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Delete' }));
|
||||
|
||||
expect(await screen.findByText('Failed to delete')).toBeInTheDocument();
|
||||
expect(screen.getByText('backup-2025-01-15.zip')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-020: the auto-backup schedule is hidden until the toggle is on', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<MAdminBackupPanel />);
|
||||
await screen.findByText('Auto-Backup');
|
||||
|
||||
const toggle = screen.getByRole('switch', { name: 'Enable auto-backup' });
|
||||
expect(toggle).toHaveAttribute('aria-checked', 'false');
|
||||
expect(screen.queryByText('Hourly')).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled();
|
||||
|
||||
await user.click(toggle);
|
||||
|
||||
expect(screen.getByText('Hourly')).toBeInTheDocument();
|
||||
expect(screen.getByText('Daily')).toBeInTheDocument();
|
||||
expect(screen.getByText('Weekly')).toBeInTheDocument();
|
||||
expect(screen.getByText('Monthly')).toBeInTheDocument();
|
||||
expect(screen.getByText('7 days')).toBeInTheDocument();
|
||||
expect(screen.getByText('Keep forever')).toBeInTheDocument();
|
||||
// Changing anything marks the form dirty
|
||||
expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled();
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-021: the hour picker renders 24h labels and names the server timezone', async () => {
|
||||
server.use(autoSettingsHandler({ ...DEFAULT_AUTO, enabled: true }, 'Europe/Berlin'));
|
||||
render(<MAdminBackupPanel />);
|
||||
|
||||
expect(await screen.findByText('Run at hour')).toBeInTheDocument();
|
||||
expect(screen.getByText('Server local time (24h format) (Timezone: Europe/Berlin)')).toBeInTheDocument();
|
||||
expect(screen.getByRole('combobox')).toHaveValue('2');
|
||||
expect(screen.getByRole('option', { name: '00:00' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('option', { name: '23:00' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-022: with a 12h user preference the hours are labelled AM/PM', async () => {
|
||||
seedStore(useSettingsStore, { settings: buildSettings({ time_format: '12h' }) });
|
||||
server.use(autoSettingsHandler({ ...DEFAULT_AUTO, enabled: true }, null));
|
||||
render(<MAdminBackupPanel />);
|
||||
|
||||
expect(await screen.findByText('Server local time (12h format)')).toBeInTheDocument();
|
||||
expect(screen.getByRole('option', { name: '12:00 AM' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('option', { name: '11:00 AM' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('option', { name: '1:00 PM' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-023: hourly hides the hour picker, weekly shows weekdays, monthly a day select', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(autoSettingsHandler({ ...DEFAULT_AUTO, enabled: true }));
|
||||
render(<MAdminBackupPanel />);
|
||||
await screen.findByText('Run at hour');
|
||||
|
||||
await user.click(screen.getByText('Hourly'));
|
||||
expect(screen.queryByText('Run at hour')).not.toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByText('Weekly'));
|
||||
expect(screen.getByText('Day of week')).toBeInTheDocument();
|
||||
expect(screen.getByText('Sun')).toBeInTheDocument();
|
||||
expect(screen.getByText('Sat')).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByText('Monthly'));
|
||||
expect(screen.queryByText('Day of week')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('Day of month')).toBeInTheDocument();
|
||||
// Hour picker plus the 1–28 day picker
|
||||
const selects = screen.getAllByRole('combobox');
|
||||
expect(selects).toHaveLength(2);
|
||||
expect(within(selects[1]).getAllByRole('option')).toHaveLength(28);
|
||||
|
||||
fireEvent.change(selects[1], { target: { value: '15' } });
|
||||
expect(selects[1]).toHaveValue('15');
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-024: saving sends the edited schedule and confirms with a toast', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: Record<string, unknown> | null = null;
|
||||
server.use(
|
||||
autoSettingsHandler({ ...DEFAULT_AUTO, enabled: true }),
|
||||
http.put('/api/backup/auto-settings', async ({ request }) => {
|
||||
body = await request.json() as Record<string, unknown>;
|
||||
return HttpResponse.json({ settings: body });
|
||||
}),
|
||||
);
|
||||
withToast();
|
||||
await screen.findByText('Run at hour');
|
||||
|
||||
await user.click(screen.getByText('Weekly'));
|
||||
await user.click(screen.getByText('Fri'));
|
||||
await user.click(screen.getByText('30 days'));
|
||||
fireEvent.change(screen.getByRole('combobox'), { target: { value: '5' } });
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
|
||||
expect(await screen.findByText('Auto-backup settings saved')).toBeInTheDocument();
|
||||
expect(body).toEqual({ enabled: true, interval: 'weekly', keep_days: 30, hour: 5, day_of_week: 5, day_of_month: 1 });
|
||||
// Server echo resets the dirty flag
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled());
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-025: a failing save toasts the settings error and keeps the form dirty', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
autoSettingsHandler({ ...DEFAULT_AUTO, enabled: true }),
|
||||
http.put('/api/backup/auto-settings', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),
|
||||
);
|
||||
withToast();
|
||||
await screen.findByText('Run at hour');
|
||||
|
||||
await user.click(screen.getByText('Weekly'));
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
|
||||
expect(await screen.findByText('Failed to save settings')).toBeInTheDocument();
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled());
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-026: an unreachable auto-settings endpoint leaves the built-in defaults in place', async () => {
|
||||
server.use(http.get('/api/backup/auto-settings', () => HttpResponse.json({}, { status: 500 })));
|
||||
withToast();
|
||||
await screen.findByText('backup-2025-01-15.zip');
|
||||
|
||||
expect(screen.getByRole('switch', { name: 'Enable auto-backup' })).toHaveAttribute('aria-checked', 'false');
|
||||
expect(screen.queryByText('Failed to load backups')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MBKP-027: an unusable server timezone falls back to the raw timestamp', async () => {
|
||||
server.use(autoSettingsHandler(DEFAULT_AUTO, 'Not/AZone'));
|
||||
render(<MAdminBackupPanel />);
|
||||
|
||||
expect(await screen.findByText('2025-01-15T10:00:00Z')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,298 @@
|
||||
// FE-MOB-MCAT-001 to FE-MOB-MCAT-016
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { render, screen, waitFor, within, fireEvent } from '../../../helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../helpers/msw/server';
|
||||
import { resetAllStores, seedStore } from '../../../helpers/store';
|
||||
import { buildAdmin, buildCategory } from '../../../helpers/factories';
|
||||
import { useAuthStore } from '../../../../src/store/authStore';
|
||||
import { ToastContainer } from '../../../../src/components/shared/Toast';
|
||||
import MAdminCategoryManager from '../../../../src/mobile/screens/admin/MAdminCategoryManager';
|
||||
|
||||
function withToast() {
|
||||
return render(<><ToastContainer /><MAdminCategoryManager /></>);
|
||||
}
|
||||
|
||||
// The preset swatches carry no label — jsdom normalises the inline hex to rgb().
|
||||
function swatch(hex: string): HTMLElement {
|
||||
const rgb = `rgb(${parseInt(hex.slice(1, 3), 16)}, ${parseInt(hex.slice(3, 5), 16)}, ${parseInt(hex.slice(5, 7), 16)})`;
|
||||
const found = Array.from(document.querySelectorAll('button')).find(b => b.style.backgroundColor === rgb);
|
||||
if (!found) throw new Error(`no colour swatch for ${hex}`);
|
||||
return found;
|
||||
}
|
||||
|
||||
describe('MAdminCategoryManager', () => {
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
|
||||
server.use(http.get('/api/categories', () => HttpResponse.json({ categories: [] })));
|
||||
});
|
||||
|
||||
it('FE-MOB-MCAT-001: shows a spinner while the list is loading, then the empty state', async () => {
|
||||
render(<MAdminCategoryManager />);
|
||||
expect(document.querySelector('.animate-spin')).toBeInTheDocument();
|
||||
|
||||
expect(await screen.findByText('No categories yet')).toBeInTheDocument();
|
||||
expect(document.querySelector('.animate-spin')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MCAT-002: renders the card head and the New Category action', async () => {
|
||||
render(<MAdminCategoryManager />);
|
||||
await screen.findByText('No categories yet');
|
||||
|
||||
expect(screen.getByText('Categories')).toBeInTheDocument();
|
||||
expect(screen.getByText('Manage categories for places')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'New Category' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MCAT-003: a failing list request surfaces the load error toast', async () => {
|
||||
server.use(http.get('/api/categories', () => HttpResponse.json({ error: 'nope' }, { status: 500 })));
|
||||
withToast();
|
||||
|
||||
expect(await screen.findByText('Failed to load categories')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MCAT-004: lists the categories from the API with name and colour badge', async () => {
|
||||
server.use(http.get('/api/categories', () => HttpResponse.json({
|
||||
categories: [
|
||||
buildCategory({ id: 1, name: 'Museum', color: '#10b981', icon: 'Landmark' }),
|
||||
buildCategory({ id: 2, name: 'Hotel', color: '#3b82f6', icon: 'BedDouble' }),
|
||||
],
|
||||
})));
|
||||
render(<MAdminCategoryManager />);
|
||||
|
||||
expect(await screen.findByText('Museum')).toBeInTheDocument();
|
||||
expect(screen.getByText('Hotel')).toBeInTheDocument();
|
||||
expect(screen.getByText('#10b981')).toBeInTheDocument();
|
||||
expect(screen.getByText('#3b82f6')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MCAT-005: New Category opens the form with the default preview label', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<MAdminCategoryManager />);
|
||||
await screen.findByText('No categories yet');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'New Category' }));
|
||||
|
||||
expect(screen.getByPlaceholderText('Category name')).toHaveValue('');
|
||||
expect(screen.getByText('Icon')).toBeInTheDocument();
|
||||
expect(screen.getByText('Color')).toBeInTheDocument();
|
||||
// Empty name falls back to the generic preview label
|
||||
expect(screen.getByText('Category')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Create' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-MOB-MCAT-006: typing a name enables Create and updates the live preview', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<MAdminCategoryManager />);
|
||||
await screen.findByText('No categories yet');
|
||||
await user.click(screen.getByRole('button', { name: 'New Category' }));
|
||||
|
||||
await user.type(screen.getByPlaceholderText('Category name'), 'Parks');
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Create' })).toBeEnabled();
|
||||
expect(screen.getByText('Parks')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MCAT-007: creating posts name, chosen icon and preset colour, and appends the row', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: Record<string, unknown> | null = null;
|
||||
server.use(http.post('/api/categories', async ({ request }) => {
|
||||
body = await request.json() as Record<string, unknown>;
|
||||
return HttpResponse.json({ category: buildCategory({ id: 77, name: 'Parks', color: '#10b981', icon: 'TreePine' }) });
|
||||
}));
|
||||
withToast();
|
||||
await screen.findByText('No categories yet');
|
||||
await user.click(screen.getByRole('button', { name: 'New Category' }));
|
||||
|
||||
await user.type(screen.getByPlaceholderText('Category name'), 'Parks');
|
||||
await user.click(screen.getByTitle('Nature'));
|
||||
await user.click(swatch('#10b981'));
|
||||
await user.click(screen.getByRole('button', { name: 'Create' }));
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Category created')).toBeInTheDocument());
|
||||
expect(body).toEqual({ name: 'Parks', color: '#10b981', icon: 'TreePine' });
|
||||
// Form closed, new row present with its colour badge
|
||||
expect(screen.queryByPlaceholderText('Category name')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('#10b981')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MCAT-008: a rejected create shows the server error message', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(http.post('/api/categories', () => HttpResponse.json({ error: 'Name already taken' }, { status: 409 })));
|
||||
withToast();
|
||||
await screen.findByText('No categories yet');
|
||||
await user.click(screen.getByRole('button', { name: 'New Category' }));
|
||||
await user.type(screen.getByPlaceholderText('Category name'), 'Parks');
|
||||
await user.click(screen.getByRole('button', { name: 'Create' }));
|
||||
|
||||
expect(await screen.findByText('Name already taken')).toBeInTheDocument();
|
||||
// Form stays open so the admin can correct the name
|
||||
expect(screen.getByPlaceholderText('Category name')).toHaveValue('Parks');
|
||||
});
|
||||
|
||||
it('FE-MOB-MCAT-009: Cancel closes the create form', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<MAdminCategoryManager />);
|
||||
await screen.findByText('No categories yet');
|
||||
await user.click(screen.getByRole('button', { name: 'New Category' }));
|
||||
expect(screen.getByPlaceholderText('Category name')).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
|
||||
expect(screen.queryByPlaceholderText('Category name')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MCAT-010: the custom colour input marks the colour as non-preset and is sent on save', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: Record<string, unknown> | null = null;
|
||||
server.use(http.post('/api/categories', async ({ request }) => {
|
||||
body = await request.json() as Record<string, unknown>;
|
||||
return HttpResponse.json({ category: buildCategory({ id: 3, name: 'Custom', color: '#123456' }) });
|
||||
}));
|
||||
withToast();
|
||||
await screen.findByText('No categories yet');
|
||||
await user.click(screen.getByRole('button', { name: 'New Category' }));
|
||||
|
||||
// The eyedropper button only forwards to the hidden colour input; drive it directly.
|
||||
const pickerButton = screen.getByTitle('Choose custom color');
|
||||
await user.click(pickerButton);
|
||||
const colorInput = document.querySelector('input[type="color"]') as HTMLInputElement;
|
||||
fireEvent.change(colorInput, { target: { value: '#123456' } });
|
||||
|
||||
expect(pickerButton.style.backgroundColor).toBe('rgb(18, 52, 86)');
|
||||
|
||||
await user.type(screen.getByPlaceholderText('Category name'), 'Custom');
|
||||
await user.click(screen.getByRole('button', { name: 'Create' }));
|
||||
|
||||
await waitFor(() => expect(body).toEqual({ name: 'Custom', color: '#123456', icon: 'MapPin' }));
|
||||
});
|
||||
|
||||
it('FE-MOB-MCAT-011: the edit button opens an inline form prefilled from the category', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(http.get('/api/categories', () => HttpResponse.json({
|
||||
categories: [buildCategory({ id: 5, name: 'Hotels', color: '#ef4444', icon: 'BedDouble' })],
|
||||
})));
|
||||
render(<MAdminCategoryManager />);
|
||||
await screen.findByText('Hotels');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Edit' }));
|
||||
|
||||
expect(screen.getByDisplayValue('Hotels')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Update' })).toBeInTheDocument();
|
||||
expect(document.querySelector('input[type="color"]')).toHaveValue('#ef4444');
|
||||
});
|
||||
|
||||
it('FE-MOB-MCAT-012: saving an edit PUTs the change and replaces the row in place', async () => {
|
||||
const user = userEvent.setup();
|
||||
let putUrl = '';
|
||||
server.use(
|
||||
http.get('/api/categories', () => HttpResponse.json({
|
||||
categories: [buildCategory({ id: 5, name: 'Hotels', color: '#ef4444', icon: 'BedDouble' })],
|
||||
})),
|
||||
http.put('/api/categories/:id', async ({ request, params }) => {
|
||||
putUrl = String(params.id);
|
||||
const b = await request.json() as Record<string, unknown>;
|
||||
return HttpResponse.json({ category: buildCategory({ id: 5, name: String(b.name), color: '#ef4444' }) });
|
||||
}),
|
||||
);
|
||||
withToast();
|
||||
await screen.findByText('Hotels');
|
||||
await user.click(screen.getByRole('button', { name: 'Edit' }));
|
||||
|
||||
const input = screen.getByDisplayValue('Hotels');
|
||||
await user.clear(input);
|
||||
await user.type(input, 'Lodging');
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }));
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Category updated')).toBeInTheDocument());
|
||||
expect(putUrl).toBe('5');
|
||||
expect(screen.getByText('Lodging')).toBeInTheDocument();
|
||||
expect(screen.queryByDisplayValue('Lodging')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MCAT-013: opening the edit form closes an open create form', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(http.get('/api/categories', () => HttpResponse.json({
|
||||
categories: [buildCategory({ id: 5, name: 'Hotels' })],
|
||||
})));
|
||||
render(<MAdminCategoryManager />);
|
||||
await screen.findByText('Hotels');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'New Category' }));
|
||||
expect(screen.getAllByPlaceholderText('Category name')).toHaveLength(1);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Edit' }));
|
||||
|
||||
// Only the inline edit form remains, prefilled
|
||||
const inputs = screen.getAllByPlaceholderText('Category name');
|
||||
expect(inputs).toHaveLength(1);
|
||||
expect(inputs[0]).toHaveValue('Hotels');
|
||||
});
|
||||
|
||||
it('FE-MOB-MCAT-014: the trash button asks for confirmation before deleting', async () => {
|
||||
const user = userEvent.setup();
|
||||
let deleted = false;
|
||||
server.use(
|
||||
http.get('/api/categories', () => HttpResponse.json({ categories: [buildCategory({ id: 9, name: 'Parks' })] })),
|
||||
http.delete('/api/categories/9', () => { deleted = true; return HttpResponse.json({ success: true }); }),
|
||||
);
|
||||
withToast();
|
||||
await screen.findByText('Parks');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Delete' }));
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
expect(within(dialog).getByText('Delete category? Places in this category will not be deleted.')).toBeInTheDocument();
|
||||
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Cancel' }));
|
||||
// The sheet stays mounted through its exit animation
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
|
||||
expect(deleted).toBe(false);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Delete' }));
|
||||
await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Delete' }));
|
||||
|
||||
await waitFor(() => expect(deleted).toBe(true));
|
||||
expect(await screen.findByText('Category deleted')).toBeInTheDocument();
|
||||
await waitFor(() => expect(screen.queryByText('Parks')).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('FE-MOB-MCAT-015: a failing delete keeps the row and shows the server error', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.get('/api/categories', () => HttpResponse.json({ categories: [buildCategory({ id: 9, name: 'Parks' })] })),
|
||||
http.delete('/api/categories/9', () => HttpResponse.json({ error: 'Category in use' }, { status: 400 })),
|
||||
);
|
||||
withToast();
|
||||
await screen.findByText('Parks');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Delete' }));
|
||||
await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Delete' }));
|
||||
|
||||
expect(await screen.findByText('Category in use')).toBeInTheDocument();
|
||||
expect(screen.getByText('Parks')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MCAT-016: picking an icon in the edit form is sent with the update', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: Record<string, unknown> | null = null;
|
||||
server.use(
|
||||
http.get('/api/categories', () => HttpResponse.json({
|
||||
categories: [buildCategory({ id: 5, name: 'Hotels', color: '#ef4444', icon: 'BedDouble' })],
|
||||
})),
|
||||
http.put('/api/categories/5', async ({ request }) => {
|
||||
body = await request.json() as Record<string, unknown>;
|
||||
return HttpResponse.json({ category: buildCategory({ id: 5, name: 'Hotels' }) });
|
||||
}),
|
||||
);
|
||||
render(<MAdminCategoryManager />);
|
||||
await screen.findByText('Hotels');
|
||||
await user.click(screen.getByRole('button', { name: 'Edit' }));
|
||||
|
||||
await user.click(screen.getByTitle('Camping'));
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }));
|
||||
|
||||
await waitFor(() => expect(body).toEqual({ name: 'Hotels', color: '#ef4444', icon: 'Tent' }));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,379 @@
|
||||
// FE-MOB-MDUS-001 to FE-MOB-MDUS-024
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { render, screen, waitFor, within, fireEvent } from '../../../helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../helpers/msw/server';
|
||||
import { resetAllStores, seedStore } from '../../../helpers/store';
|
||||
import { buildAdmin } from '../../../helpers/factories';
|
||||
import { useAuthStore } from '../../../../src/store/authStore';
|
||||
import { ToastContainer } from '../../../../src/components/shared/Toast';
|
||||
import MAdminDefaultUserSettings from '../../../../src/mobile/screens/admin/MAdminDefaultUserSettings';
|
||||
|
||||
// The live tile preview would pull Leaflet into jsdom; the panel only needs it to render.
|
||||
vi.mock('../../../../src/components/Map/MapView', () => ({
|
||||
MapView: ({ tileUrl }: { tileUrl?: string }) => <div data-testid="map-preview" data-tile={tileUrl} />,
|
||||
}));
|
||||
|
||||
const MAPBOX_STANDARD = 'mapbox://styles/mapbox/standard';
|
||||
const OFM_LIBERTY = 'https://tiles.openfreemap.org/styles/liberty';
|
||||
|
||||
/** Stateful stand-in for the admin defaults endpoint: PUT merges, null deletes. */
|
||||
function stubDefaults(initial: Record<string, unknown> = {}) {
|
||||
const state: Record<string, unknown> = { ...initial };
|
||||
const puts: Record<string, unknown>[] = [];
|
||||
server.use(
|
||||
http.get('/api/admin/default-user-settings', () => HttpResponse.json(state)),
|
||||
http.put('/api/admin/default-user-settings', async ({ request }) => {
|
||||
const body = await request.json() as Record<string, unknown>;
|
||||
puts.push(body);
|
||||
for (const [key, value] of Object.entries(body)) {
|
||||
if (value === null) delete state[key];
|
||||
else state[key] = value;
|
||||
}
|
||||
return HttpResponse.json({ ...state });
|
||||
}),
|
||||
);
|
||||
return { puts, state };
|
||||
}
|
||||
|
||||
function withToast() {
|
||||
return render(<><ToastContainer /><MAdminDefaultUserSettings /></>);
|
||||
}
|
||||
|
||||
/** The reset link lives inside the field label next to its caption. */
|
||||
function resetLink(label: string): HTMLElement {
|
||||
const holder = screen.getAllByText(label).find(el => el.querySelector('button'));
|
||||
if (!holder) throw new Error(`no reset link next to "${label}"`);
|
||||
return within(holder).getByRole('button', { name: 'reset' });
|
||||
}
|
||||
|
||||
describe('MAdminDefaultUserSettings', () => {
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
|
||||
stubDefaults();
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-001: shows the loading placeholder until the defaults arrive', async () => {
|
||||
render(<MAdminDefaultUserSettings />);
|
||||
expect(screen.getByText('Loading…')).toBeInTheDocument();
|
||||
|
||||
expect(await screen.findByText('Default User Settings')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Loading…')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-002: renders every default field with no preselected segment when nothing is set', async () => {
|
||||
render(<MAdminDefaultUserSettings />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
expect(screen.getByText(/Set instance-wide defaults/)).toBeInTheDocument();
|
||||
for (const name of ['Light', 'Dark', 'Auto', '°C Celsius', 'km Metric', '24h (14:30)']) {
|
||||
expect(screen.getByRole('tab', { name })).toHaveAttribute('aria-selected', 'false');
|
||||
}
|
||||
// No default chosen yet → no reset links anywhere
|
||||
expect(screen.queryByRole('button', { name: 'reset' })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Display currency' })).toBeInTheDocument();
|
||||
expect(screen.getByTestId('map-preview')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-003: a failing load still renders the (empty) panel', async () => {
|
||||
server.use(http.get('/api/admin/default-user-settings', () => HttpResponse.json({}, { status: 500 })));
|
||||
render(<MAdminDefaultUserSettings />);
|
||||
|
||||
expect(await screen.findByText('Default User Settings')).toBeInTheDocument();
|
||||
expect(screen.getByRole('tab', { name: 'Standard (free)' })).toHaveAttribute('aria-selected', 'true');
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-004: picking a colour mode saves it and shows the confirmation toast', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults();
|
||||
withToast();
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
await user.click(screen.getByRole('tab', { name: 'Dark' }));
|
||||
|
||||
expect(await screen.findByText('Default saved')).toBeInTheDocument();
|
||||
expect(puts).toEqual([{ dark_mode: 'dark' }]);
|
||||
await waitFor(() => expect(screen.getByRole('tab', { name: 'Dark' })).toHaveAttribute('aria-selected', 'true'));
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-005: a legacy boolean dark_mode still highlights the matching segment', async () => {
|
||||
stubDefaults({ dark_mode: true });
|
||||
render(<MAdminDefaultUserSettings />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
expect(screen.getByRole('tab', { name: 'Dark' })).toHaveAttribute('aria-selected', 'true');
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-006: dark_mode false maps to Light, "auto" maps to Auto', async () => {
|
||||
stubDefaults({ dark_mode: false });
|
||||
const { unmount } = render(<MAdminDefaultUserSettings />);
|
||||
await screen.findByText('Default User Settings');
|
||||
expect(screen.getByRole('tab', { name: 'Light' })).toHaveAttribute('aria-selected', 'true');
|
||||
unmount();
|
||||
|
||||
stubDefaults({ dark_mode: 'auto' });
|
||||
render(<MAdminDefaultUserSettings />);
|
||||
await screen.findByText('Default User Settings');
|
||||
expect(screen.getByRole('tab', { name: 'Auto' })).toHaveAttribute('aria-selected', 'true');
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-007: unit and time-format segments each save their own key', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults();
|
||||
render(<MAdminDefaultUserSettings />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
await user.click(screen.getByRole('tab', { name: '°F Fahrenheit' }));
|
||||
await waitFor(() => expect(screen.getByRole('tab', { name: '°F Fahrenheit' })).toHaveAttribute('aria-selected', 'true'));
|
||||
await user.click(screen.getByRole('tab', { name: 'mi Imperial' }));
|
||||
await waitFor(() => expect(screen.getByRole('tab', { name: 'mi Imperial' })).toHaveAttribute('aria-selected', 'true'));
|
||||
await user.click(screen.getByRole('tab', { name: '12h (2:30 PM)' }));
|
||||
|
||||
await waitFor(() => expect(puts).toEqual([
|
||||
{ temperature_unit: 'fahrenheit' },
|
||||
{ distance_unit: 'imperial' },
|
||||
{ time_format: '12h' },
|
||||
]));
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-008: a set default gets a reset link that clears it server-side', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts, state } = stubDefaults({ temperature_unit: 'celsius' });
|
||||
withToast();
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
expect(screen.getByRole('tab', { name: '°C Celsius' })).toHaveAttribute('aria-selected', 'true');
|
||||
await user.click(resetLink('Temperature Unit'));
|
||||
|
||||
expect(await screen.findByText('Reset to built-in default')).toBeInTheDocument();
|
||||
expect(puts).toEqual([{ temperature_unit: null }]);
|
||||
expect(state.temperature_unit).toBeUndefined();
|
||||
await waitFor(() => expect(screen.getByRole('tab', { name: '°C Celsius' })).toHaveAttribute('aria-selected', 'false'));
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-009: the currency row shows the symbol and the picker saves the chosen code', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults({ default_currency: 'USD' });
|
||||
render(<MAdminDefaultUserSettings />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'USD $' }));
|
||||
const sheet = await screen.findByRole('dialog');
|
||||
await user.click(within(sheet).getByRole('button', { name: 'EUR €' }));
|
||||
|
||||
await waitFor(() => expect(puts).toEqual([{ default_currency: 'EUR' }]));
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'EUR €' })).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-010: the blur-booking-codes toggle saves a boolean default', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults();
|
||||
render(<MAdminDefaultUserSettings />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
const toggle = screen.getByRole('switch', { name: 'Blur Booking Codes' });
|
||||
expect(toggle).toHaveAttribute('aria-checked', 'false');
|
||||
await user.click(toggle);
|
||||
|
||||
await waitFor(() => expect(puts).toEqual([{ blur_booking_codes: true }]));
|
||||
await waitFor(() => expect(screen.getByRole('switch', { name: 'Blur Booking Codes' })).toHaveAttribute('aria-checked', 'true'));
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-011: the tile URL is saved on blur and handed to the preview map', async () => {
|
||||
const { puts } = stubDefaults();
|
||||
render(<MAdminDefaultUserSettings />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
// Typed through fireEvent: the {z}/{x}/{y} placeholders collide with userEvent's key syntax
|
||||
const input = screen.getByPlaceholderText('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
|
||||
fireEvent.change(input, { target: { value: 'https://tiles.example.org/{z}/{x}/{y}.png' } });
|
||||
fireEvent.blur(input);
|
||||
|
||||
await waitFor(() => expect(puts).toEqual([{ map_tile_url: 'https://tiles.example.org/{z}/{x}/{y}.png' }]));
|
||||
expect(screen.getByTestId('map-preview')).toHaveAttribute('data-tile', 'https://tiles.example.org/{z}/{x}/{y}.png');
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-012: the tile preset sheet fills the URL field and saves it', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults();
|
||||
render(<MAdminDefaultUserSettings />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Select template...' }));
|
||||
const sheet = await screen.findByRole('dialog');
|
||||
await user.click(within(sheet).getByRole('button', { name: 'CartoDB Dark' }));
|
||||
|
||||
const url = 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png';
|
||||
await waitFor(() => expect(puts).toEqual([{ map_tile_url: url }]));
|
||||
expect(screen.getByPlaceholderText('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png')).toHaveValue(url);
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'CartoDB Dark' })).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-013: resetting the tile URL clears the input as well', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults({ map_tile_url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' });
|
||||
render(<MAdminDefaultUserSettings />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
expect(screen.getByRole('button', { name: 'OpenStreetMap DE' })).toBeInTheDocument();
|
||||
await user.click(resetLink('Map Template'));
|
||||
|
||||
await waitFor(() => expect(puts).toEqual([{ map_tile_url: null }]));
|
||||
await waitFor(() => expect(screen.getByPlaceholderText('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png')).toHaveValue(''));
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-014: leaflet hides the GL-only token and style fields', async () => {
|
||||
render(<MAdminDefaultUserSettings />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
expect(screen.getByRole('tab', { name: 'Standard (free)' })).toHaveAttribute('aria-selected', 'true');
|
||||
expect(screen.queryByText('Map style')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Shared Mapbox token')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-015: switching to Mapbox stores the provider together with its own style slot', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults();
|
||||
render(<MAdminDefaultUserSettings />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
await user.click(screen.getByRole('tab', { name: 'Mapbox (3D)' }));
|
||||
|
||||
await waitFor(() => expect(puts).toEqual([{ map_provider: 'mapbox-gl', mapbox_style: MAPBOX_STANDARD }]));
|
||||
expect(await screen.findByText('Shared Mapbox token')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Mapbox Standard' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('switch', { name: '3D buildings & terrain' })).toHaveAttribute('aria-checked', 'true');
|
||||
expect(screen.getByRole('switch', { name: 'High-quality mode' })).toHaveAttribute('aria-checked', 'false');
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-016: switching to MapLibre stores the OpenFreeMap default in maplibre_style', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults();
|
||||
render(<MAdminDefaultUserSettings />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
await user.click(screen.getByRole('tab', { name: 'MapLibre (OpenFreeMap)' }));
|
||||
|
||||
await waitFor(() => expect(puts).toEqual([{ map_provider: 'maplibre-gl', maplibre_style: OFM_LIBERTY }]));
|
||||
// MapLibre needs no shared token
|
||||
expect(screen.queryByText('Shared Mapbox token')).not.toBeInTheDocument();
|
||||
expect(await screen.findByRole('button', { name: 'OpenFreeMap Liberty' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-017: a Mapbox default holding an OpenFreeMap style falls back to the Mapbox standard', async () => {
|
||||
stubDefaults({ map_provider: 'mapbox-gl', mapbox_style: OFM_LIBERTY });
|
||||
render(<MAdminDefaultUserSettings />);
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Mapbox Standard' })).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue(MAPBOX_STANDARD)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-018: the shared Mapbox token is stored on blur and cleared by its reset link', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults({ map_provider: 'mapbox-gl', mapbox_access_token: 'pk.old' });
|
||||
render(<MAdminDefaultUserSettings />);
|
||||
await screen.findByText('Shared Mapbox token');
|
||||
|
||||
const input = screen.getByPlaceholderText('pk.eyJ…');
|
||||
expect(input).toHaveValue('pk.old');
|
||||
await user.clear(input);
|
||||
await user.type(input, 'pk.new');
|
||||
input.blur();
|
||||
await waitFor(() => expect(puts).toEqual([{ mapbox_access_token: 'pk.new' }]));
|
||||
|
||||
await user.click(resetLink('Shared Mapbox token'));
|
||||
await waitFor(() => expect(puts).toHaveLength(2));
|
||||
expect(puts[1]).toEqual({ mapbox_access_token: null });
|
||||
await waitFor(() => expect(screen.getByPlaceholderText('pk.eyJ…')).toHaveValue(''));
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-019: a hand-typed MapLibre style is normalised to OpenFreeMap on blur', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults({ map_provider: 'maplibre-gl', maplibre_style: OFM_LIBERTY });
|
||||
render(<MAdminDefaultUserSettings />);
|
||||
await screen.findByText('Map style');
|
||||
|
||||
const input = screen.getByDisplayValue(OFM_LIBERTY);
|
||||
await user.clear(input);
|
||||
await user.type(input, 'https://example.com/custom.json');
|
||||
input.blur();
|
||||
|
||||
await waitFor(() => expect(puts).toEqual([{ maplibre_style: OFM_LIBERTY }]));
|
||||
expect(input).toHaveValue(OFM_LIBERTY);
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-020: the style sheet writes the picked preset into the active provider slot', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults({ map_provider: 'mapbox-gl', mapbox_style: MAPBOX_STANDARD });
|
||||
render(<MAdminDefaultUserSettings />);
|
||||
await screen.findByText('Map style');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Mapbox Standard' }));
|
||||
const sheet = await screen.findByRole('dialog');
|
||||
await user.click(within(sheet).getByRole('button', { name: 'Navigation Night' }));
|
||||
|
||||
const url = 'mapbox://styles/mapbox/navigation-night-v1';
|
||||
await waitFor(() => expect(puts).toEqual([{ mapbox_style: url }]));
|
||||
expect(screen.getByDisplayValue(url)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-021: resetting the style restores the provider default in the field', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults({ map_provider: 'mapbox-gl', mapbox_style: 'mapbox://styles/mapbox/dark-v11' });
|
||||
render(<MAdminDefaultUserSettings />);
|
||||
await screen.findByText('Map style');
|
||||
|
||||
await user.click(resetLink('Map style'));
|
||||
|
||||
await waitFor(() => expect(puts).toEqual([{ mapbox_style: null }]));
|
||||
await waitFor(() => expect(screen.getByDisplayValue(MAPBOX_STANDARD)).toBeInTheDocument());
|
||||
expect(screen.getByRole('button', { name: 'Mapbox Standard' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-022: the Mapbox 3D and quality toggles save their own keys', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { puts } = stubDefaults({ map_provider: 'mapbox-gl', mapbox_3d_enabled: true, mapbox_quality_mode: false });
|
||||
render(<MAdminDefaultUserSettings />);
|
||||
await screen.findByText('Map style');
|
||||
|
||||
await user.click(screen.getByRole('switch', { name: '3D buildings & terrain' }));
|
||||
await waitFor(() => expect(screen.getByRole('switch', { name: '3D buildings & terrain' })).toHaveAttribute('aria-checked', 'false'));
|
||||
await user.click(screen.getByRole('switch', { name: 'High-quality mode' }));
|
||||
|
||||
await waitFor(() => expect(puts).toEqual([{ mapbox_3d_enabled: false }, { mapbox_quality_mode: true }]));
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-023: a rejected save surfaces the request error instead of a success toast', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.get('/api/admin/default-user-settings', () => HttpResponse.json({})),
|
||||
http.put('/api/admin/default-user-settings', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),
|
||||
);
|
||||
withToast();
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
await user.click(screen.getByRole('tab', { name: 'Dark' }));
|
||||
|
||||
expect(await screen.findByText(/Request failed with status code 500/)).toBeInTheDocument();
|
||||
expect(screen.queryByText('Default saved')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MDUS-024: a rejected reset keeps the value and reports the failure', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.get('/api/admin/default-user-settings', () => HttpResponse.json({ temperature_unit: 'celsius' })),
|
||||
http.put('/api/admin/default-user-settings', () => HttpResponse.json({ error: 'nope' }, { status: 503 })),
|
||||
);
|
||||
withToast();
|
||||
await screen.findByText('Default User Settings');
|
||||
|
||||
await user.click(resetLink('Temperature Unit'));
|
||||
|
||||
expect(await screen.findByText(/Request failed with status code 503/)).toBeInTheDocument();
|
||||
expect(screen.queryByText('Reset to built-in default')).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('tab', { name: '°C Celsius' })).toHaveAttribute('aria-selected', 'true');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,337 @@
|
||||
// FE-MOB-ADEV-001 to FE-MOB-ADEV-015
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen, waitFor } from '../../../helpers/render';
|
||||
import { server } from '../../../helpers/msw/server';
|
||||
import { resetAllStores, seedStore } from '../../../helpers/store';
|
||||
import { buildAdmin } from '../../../helpers/factories';
|
||||
import { useAuthStore } from '../../../../src/store/authStore';
|
||||
import { ToastContainer } from '../../../../src/components/shared/Toast';
|
||||
import MAdminDevNotificationsPanel from '../../../../src/mobile/screens/admin/MAdminDevNotificationsPanel';
|
||||
|
||||
const ADMIN = buildAdmin({ id: 7, username: 'testadmin', email: 'admin@example.com' });
|
||||
|
||||
function renderPanel() {
|
||||
return render(
|
||||
<>
|
||||
<ToastContainer />
|
||||
<MAdminDevNotificationsPanel />
|
||||
</>,
|
||||
);
|
||||
}
|
||||
|
||||
/** Captures every POST body the panel sends while a test runs. */
|
||||
function captureSends() {
|
||||
const bodies: Record<string, unknown>[] = [];
|
||||
server.use(
|
||||
http.post('/api/admin/dev/test-notification', async ({ request }) => {
|
||||
bodies.push((await request.json()) as Record<string, unknown>);
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
return bodies;
|
||||
}
|
||||
|
||||
function clickButton(user: ReturnType<typeof userEvent.setup>, label: string) {
|
||||
return user.click(screen.getByText(label).closest('button')!);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
seedStore(useAuthStore, { isAuthenticated: true, user: ADMIN });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
describe('MAdminDevNotificationsPanel', () => {
|
||||
it('FE-MOB-ADEV-001: renders the dev badge and all four sections once the data is in', async () => {
|
||||
renderPanel();
|
||||
|
||||
expect(screen.getByText('DEV ONLY')).toBeInTheDocument();
|
||||
expect(screen.getByText('Notification Testing')).toBeInTheDocument();
|
||||
expect(screen.getByText('Type Testing')).toBeInTheDocument();
|
||||
expect(screen.getByText('Admin-Scoped Events')).toBeInTheDocument();
|
||||
await screen.findByText('Trip-Scoped Events');
|
||||
await screen.findByText('User-Scoped Events');
|
||||
});
|
||||
|
||||
it('FE-MOB-ADEV-002: the trip selector lists the trips from the API and preselects the first', async () => {
|
||||
renderPanel();
|
||||
await screen.findByText('Trip-Scoped Events');
|
||||
|
||||
const [tripSelect] = screen.getAllByRole('combobox');
|
||||
const labels = Array.from(tripSelect.querySelectorAll('option')).map((o) => o.textContent);
|
||||
expect(labels).toContain('Paris Adventure');
|
||||
expect(labels).toContain('Tokyo Trip');
|
||||
expect((tripSelect as HTMLSelectElement).value).toBe(
|
||||
(tripSelect.querySelector('option') as HTMLOptionElement).value,
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-MOB-ADEV-003: the user selector shows username and email of every user', async () => {
|
||||
renderPanel();
|
||||
await screen.findByText('User-Scoped Events');
|
||||
|
||||
const userSelect = screen.getAllByRole('combobox')[1];
|
||||
const labels = Array.from(userSelect.querySelectorAll('option')).map((o) => o.textContent ?? '');
|
||||
expect(labels).toContain('admin (admin@example.com)');
|
||||
expect(labels).toContain('alice (alice@example.com)');
|
||||
});
|
||||
|
||||
it('FE-MOB-ADEV-004: the type-testing buttons send the documented payloads', async () => {
|
||||
const bodies = captureSends();
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
await screen.findByText('Type Testing');
|
||||
|
||||
await clickButton(user, 'Simple → Me');
|
||||
await waitFor(() => expect(bodies).toHaveLength(1));
|
||||
expect(bodies[0]).toEqual({ event: 'test_simple', scope: 'user', targetId: 7, params: {} });
|
||||
|
||||
await clickButton(user, 'Boolean → Me');
|
||||
await waitFor(() => expect(bodies).toHaveLength(2));
|
||||
expect(bodies[1]).toMatchObject({
|
||||
event: 'test_boolean',
|
||||
scope: 'user',
|
||||
targetId: 7,
|
||||
inApp: {
|
||||
type: 'boolean',
|
||||
positiveCallback: { action: 'test_approve', payload: {} },
|
||||
negativeCallback: { action: 'test_deny', payload: {} },
|
||||
},
|
||||
});
|
||||
|
||||
await clickButton(user, 'Navigate → Me');
|
||||
await waitFor(() => expect(bodies).toHaveLength(3));
|
||||
expect(bodies[2]).toMatchObject({ event: 'test_navigate', scope: 'user', targetId: 7 });
|
||||
|
||||
await clickButton(user, 'Simple → All Admins');
|
||||
await waitFor(() => expect(bodies).toHaveLength(4));
|
||||
expect(bodies[3]).toMatchObject({ event: 'test_simple', scope: 'admin', targetId: 0 });
|
||||
});
|
||||
|
||||
it('FE-MOB-ADEV-005: every trip-scoped button targets the selected trip with its own params', async () => {
|
||||
const bodies = captureSends();
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
await screen.findByText('Trip-Scoped Events');
|
||||
|
||||
const [tripSelect] = screen.getAllByRole('combobox');
|
||||
const tripId = Number((tripSelect as HTMLSelectElement).value);
|
||||
const tripTitle = tripSelect.querySelector('option')!.textContent;
|
||||
|
||||
await clickButton(user, 'booking_change');
|
||||
await waitFor(() => expect(bodies).toHaveLength(1));
|
||||
expect(bodies[0]).toEqual({
|
||||
event: 'booking_change',
|
||||
scope: 'trip',
|
||||
targetId: tripId,
|
||||
params: {
|
||||
actor: 'testadmin',
|
||||
trip: tripTitle,
|
||||
booking: 'Test Hotel',
|
||||
type: 'hotel',
|
||||
tripId: String(tripId),
|
||||
},
|
||||
});
|
||||
|
||||
await clickButton(user, 'trip_reminder');
|
||||
await waitFor(() => expect(bodies).toHaveLength(2));
|
||||
expect(bodies[1]).toEqual({
|
||||
event: 'trip_reminder',
|
||||
scope: 'trip',
|
||||
targetId: tripId,
|
||||
params: { trip: tripTitle, tripId: String(tripId) },
|
||||
});
|
||||
|
||||
await clickButton(user, 'photos_shared');
|
||||
await waitFor(() => expect(bodies).toHaveLength(3));
|
||||
expect(bodies[2]).toMatchObject({ event: 'photos_shared', params: { count: '5' } });
|
||||
|
||||
await clickButton(user, 'collab_message');
|
||||
await waitFor(() => expect(bodies).toHaveLength(4));
|
||||
expect(bodies[3]).toMatchObject({
|
||||
event: 'collab_message',
|
||||
params: { preview: 'This is a test message preview.' },
|
||||
});
|
||||
|
||||
await clickButton(user, 'packing_tagged');
|
||||
await waitFor(() => expect(bodies).toHaveLength(5));
|
||||
expect(bodies[4]).toMatchObject({ event: 'packing_tagged', params: { category: 'Clothing' } });
|
||||
});
|
||||
|
||||
it('FE-MOB-ADEV-006: the user-scoped buttons target the selected recipient', async () => {
|
||||
const bodies = captureSends();
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
await screen.findByText('User-Scoped Events');
|
||||
|
||||
const userSelect = screen.getAllByRole('combobox')[1] as HTMLSelectElement;
|
||||
const recipientId = Number(userSelect.value);
|
||||
|
||||
await clickButton(user, 'trip_invite');
|
||||
await waitFor(() => expect(bodies).toHaveLength(1));
|
||||
expect(bodies[0]).toMatchObject({
|
||||
event: 'trip_invite',
|
||||
scope: 'user',
|
||||
targetId: recipientId,
|
||||
params: { actor: 'testadmin', invitee: 'admin@example.com' },
|
||||
});
|
||||
|
||||
await clickButton(user, 'vacay_invite');
|
||||
await waitFor(() => expect(bodies).toHaveLength(2));
|
||||
expect(bodies[1]).toEqual({
|
||||
event: 'vacay_invite',
|
||||
scope: 'user',
|
||||
targetId: recipientId,
|
||||
params: { actor: 'testadmin', planId: '1' },
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-MOB-ADEV-007: the admin-scoped button announces a fake version', async () => {
|
||||
const bodies = captureSends();
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
await screen.findByText('Admin-Scoped Events');
|
||||
|
||||
await clickButton(user, 'version_available');
|
||||
await waitFor(() => expect(bodies).toHaveLength(1));
|
||||
expect(bodies[0]).toEqual({
|
||||
event: 'version_available',
|
||||
scope: 'admin',
|
||||
targetId: 0,
|
||||
params: { version: '9.9.9-test' },
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-MOB-ADEV-008: changing the trip selector changes the payload target', async () => {
|
||||
const bodies = captureSends();
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
await screen.findByText('Trip-Scoped Events');
|
||||
|
||||
const [tripSelect] = screen.getAllByRole('combobox');
|
||||
const tokyo = Array.from(tripSelect.querySelectorAll('option')).find(
|
||||
(o) => o.textContent === 'Tokyo Trip',
|
||||
)!;
|
||||
await user.selectOptions(tripSelect, tokyo.value);
|
||||
await clickButton(user, 'trip_reminder');
|
||||
|
||||
await waitFor(() => expect(bodies).toHaveLength(1));
|
||||
expect(bodies[0]).toMatchObject({ targetId: Number(tokyo.value), params: { trip: 'Tokyo Trip' } });
|
||||
});
|
||||
|
||||
it('FE-MOB-ADEV-009: changing the user selector changes the recipient', async () => {
|
||||
const bodies = captureSends();
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
await screen.findByText('User-Scoped Events');
|
||||
|
||||
const userSelect = screen.getAllByRole('combobox')[1];
|
||||
const alice = Array.from(userSelect.querySelectorAll('option')).find(
|
||||
(o) => o.textContent?.startsWith('alice'),
|
||||
)!;
|
||||
await user.selectOptions(userSelect, alice.value);
|
||||
await clickButton(user, 'trip_invite');
|
||||
|
||||
await waitFor(() => expect(bodies).toHaveLength(1));
|
||||
expect(bodies[0]).toMatchObject({
|
||||
targetId: Number(alice.value),
|
||||
params: { invitee: 'alice@example.com' },
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-MOB-ADEV-010: a successful send raises a toast naming the fired button', async () => {
|
||||
captureSends();
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
await screen.findByText('Type Testing');
|
||||
|
||||
await clickButton(user, 'Simple → Me');
|
||||
expect(await screen.findByText('Sent: simple-me')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ADEV-011: a failing send raises an error toast', async () => {
|
||||
server.use(
|
||||
http.post('/api/admin/dev/test-notification', () => HttpResponse.json({}, { status: 500 })),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
await screen.findByText('Type Testing');
|
||||
|
||||
await clickButton(user, 'Simple → Me');
|
||||
expect(await screen.findByText(/failed|error/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ADEV-012: every button is disabled while a send is in flight', async () => {
|
||||
server.use(
|
||||
http.post('/api/admin/dev/test-notification', async () => {
|
||||
await new Promise(() => {});
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
await screen.findByText('Type Testing');
|
||||
|
||||
void clickButton(user, 'Simple → Me');
|
||||
|
||||
await waitFor(() => {
|
||||
const buttons = screen.getAllByRole('button');
|
||||
expect(buttons.length).toBeGreaterThan(1);
|
||||
buttons.forEach((btn) => expect(btn).toBeDisabled());
|
||||
});
|
||||
// The fired button shows its own spinner
|
||||
expect(document.querySelector('.animate-spin')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ADEV-013: the scoped sections stay hidden when both lookups fail', async () => {
|
||||
server.use(
|
||||
http.get('/api/trips', () => HttpResponse.json({}, { status: 500 })),
|
||||
http.get('/api/admin/users', () => HttpResponse.json({}, { status: 500 })),
|
||||
);
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('Type Testing');
|
||||
await waitFor(() => expect(screen.queryAllByRole('combobox')).toHaveLength(0));
|
||||
expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ADEV-014: bare arrays are accepted as well as the wrapped payloads', async () => {
|
||||
server.use(
|
||||
http.get('/api/trips', () => HttpResponse.json([{ id: 55, title: 'Bare Trip' }])),
|
||||
http.get('/api/admin/users', () =>
|
||||
HttpResponse.json([{ id: 66, username: 'bare', email: 'bare@example.com' }]),
|
||||
),
|
||||
);
|
||||
renderPanel();
|
||||
await screen.findByText('Trip-Scoped Events');
|
||||
|
||||
const [tripSelect, userSelect] = screen.getAllByRole('combobox') as HTMLSelectElement[];
|
||||
expect(tripSelect.value).toBe('55');
|
||||
expect(screen.getByText('Bare Trip')).toBeInTheDocument();
|
||||
expect(userSelect.value).toBe('66');
|
||||
expect(screen.getByText('bare (bare@example.com)')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ADEV-015: without trips or a signed-in user the invite falls back to defaults', async () => {
|
||||
const bodies = captureSends();
|
||||
server.use(http.get('/api/trips', () => HttpResponse.json({ trips: [] })));
|
||||
resetAllStores();
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
await screen.findByText('User-Scoped Events');
|
||||
|
||||
await clickButton(user, 'trip_invite');
|
||||
|
||||
await waitFor(() => expect(bodies).toHaveLength(1));
|
||||
expect(bodies[0]).toMatchObject({
|
||||
event: 'trip_invite',
|
||||
params: { actor: 'Admin', trip: 'Test Trip', tripId: '0' },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,279 @@
|
||||
// FE-MOB-AGH-001 to FE-MOB-AGH-018
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen, waitFor } from '../../../helpers/render';
|
||||
import { server } from '../../../helpers/msw/server';
|
||||
import { resetAllStores } from '../../../helpers/store';
|
||||
import MAdminGitHubPanel from '../../../../src/mobile/screens/admin/MAdminGitHubPanel';
|
||||
|
||||
interface ReleaseOverrides {
|
||||
id?: number;
|
||||
tag_name?: string;
|
||||
name?: string | null;
|
||||
body?: string | null;
|
||||
published_at?: string | null;
|
||||
created_at?: string;
|
||||
prerelease?: boolean;
|
||||
author?: { login: string } | null;
|
||||
}
|
||||
|
||||
function buildRelease(overrides: ReleaseOverrides = {}) {
|
||||
return {
|
||||
id: 1,
|
||||
tag_name: 'v1.0.0',
|
||||
name: 'Initial Release',
|
||||
body: null,
|
||||
published_at: '2025-01-15T12:00:00Z',
|
||||
created_at: '2025-01-15T12:00:00Z',
|
||||
prerelease: false,
|
||||
author: { login: 'mauriceboe' },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const PAGE_1 = Array.from({ length: 10 }, (_, i) => buildRelease({ id: i + 1, tag_name: `v1.${i}.0` }));
|
||||
const PAGE_2 = Array.from({ length: 3 }, (_, i) => buildRelease({ id: 100 + i, tag_name: `v0.${i}.0` }));
|
||||
|
||||
function releasesRespondWith(payload: unknown) {
|
||||
server.use(http.get('/api/admin/github-releases', () => HttpResponse.json(payload)));
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
releasesRespondWith([]);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
async function renderPanel(props: { isPrerelease?: boolean } = {}) {
|
||||
const view = render(<MAdminGitHubPanel {...props} />);
|
||||
await waitFor(() => expect(document.querySelector('.animate-spin')).not.toBeInTheDocument());
|
||||
return view;
|
||||
}
|
||||
|
||||
describe('MAdminGitHubPanel', () => {
|
||||
it('FE-MOB-AGH-001: renders the six support cards with their external hrefs', async () => {
|
||||
await renderPanel();
|
||||
|
||||
expect(screen.getByText('Ko-fi').closest('a')).toHaveAttribute('href', 'https://ko-fi.com/mauriceboe');
|
||||
expect(screen.getByText('Buy Me a Coffee').closest('a')).toHaveAttribute(
|
||||
'href',
|
||||
'https://buymeacoffee.com/mauriceboe',
|
||||
);
|
||||
const discord = screen.getByText('Discord').closest('a')!;
|
||||
expect(discord).toHaveAttribute('href', 'https://discord.gg/NhZBDSd4qW');
|
||||
expect(discord).toHaveAttribute('target', '_blank');
|
||||
expect(discord).toHaveAttribute('rel', 'noopener noreferrer');
|
||||
expect(screen.getByText('Report a Bug')).toBeInTheDocument();
|
||||
expect(screen.getByText('Feature Request')).toBeInTheDocument();
|
||||
expect(screen.getByText('Wiki').closest('a')).toHaveAttribute('href', 'https://github.com/mauriceboe/TREK/wiki');
|
||||
expect(screen.getAllByText('Helps me keep building TREK')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('FE-MOB-AGH-002: shows a spinner while the releases request is in flight', () => {
|
||||
server.use(
|
||||
http.get('/api/admin/github-releases', async () => {
|
||||
await new Promise(() => {});
|
||||
return HttpResponse.json([]);
|
||||
}),
|
||||
);
|
||||
render(<MAdminGitHubPanel />);
|
||||
|
||||
expect(document.querySelector('.animate-spin')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Release History')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AGH-003: renders the error card with the axios message when the request fails', async () => {
|
||||
server.use(
|
||||
http.get('/api/admin/github-releases', () => HttpResponse.json({ message: 'boom' }, { status: 500 })),
|
||||
);
|
||||
render(<MAdminGitHubPanel />);
|
||||
|
||||
await screen.findByText('Failed to load releases');
|
||||
expect(screen.getByText(/500/)).toBeInTheDocument();
|
||||
expect(screen.queryByText('Release History')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AGH-004: renders the timeline header with the repo subtitle and the GitHub link', async () => {
|
||||
releasesRespondWith([buildRelease()]);
|
||||
await renderPanel();
|
||||
|
||||
expect(screen.getByText('Release History')).toBeInTheDocument();
|
||||
expect(screen.getByText('Latest updates from mauriceboe/TREK')).toBeInTheDocument();
|
||||
expect(screen.getByText('GitHub').closest('a')).toHaveAttribute(
|
||||
'href',
|
||||
'https://github.com/mauriceboe/TREK/releases',
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-MOB-AGH-005: marks only the first release as latest and shows the release name and author', async () => {
|
||||
releasesRespondWith([
|
||||
buildRelease({ id: 1, tag_name: 'v2.0.0', name: 'Big Bang' }),
|
||||
buildRelease({ id: 2, tag_name: 'v1.9.0', name: 'v1.9.0' }),
|
||||
]);
|
||||
await renderPanel();
|
||||
|
||||
expect(screen.getAllByText('Latest')).toHaveLength(1);
|
||||
expect(screen.getByText('v2.0.0')).toBeInTheDocument();
|
||||
// name === tag_name on the second release, so it is not repeated
|
||||
expect(screen.getByText('Big Bang')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('v1.9.0')).toHaveLength(1);
|
||||
expect(screen.getAllByText('by mauriceboe')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('FE-MOB-AGH-006: falls back to created_at when published_at is null and hides a missing author', async () => {
|
||||
releasesRespondWith([
|
||||
buildRelease({ published_at: null, created_at: '2024-03-02T08:00:00Z', author: null, name: null }),
|
||||
]);
|
||||
await renderPanel();
|
||||
|
||||
expect(screen.getByText('Mar 2, 2024')).toBeInTheDocument();
|
||||
expect(screen.queryByText(/by /)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AGH-007: hides prereleases unless the panel runs in prerelease mode', async () => {
|
||||
releasesRespondWith([
|
||||
buildRelease({ id: 1, tag_name: 'v3.0.0-beta.1', prerelease: true }),
|
||||
buildRelease({ id: 2, tag_name: 'v2.9.0' }),
|
||||
]);
|
||||
await renderPanel();
|
||||
|
||||
expect(screen.queryByText('v3.0.0-beta.1')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('v2.9.0')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AGH-008: prerelease mode shows the pre-release badge', async () => {
|
||||
releasesRespondWith([buildRelease({ id: 1, tag_name: 'v3.0.0-beta.1', prerelease: true })]);
|
||||
await renderPanel({ isPrerelease: true });
|
||||
|
||||
expect(screen.getByText('v3.0.0-beta.1')).toBeInTheDocument();
|
||||
expect(screen.getByText('Pre-release')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AGH-009: no toggle is offered for a release without a body', async () => {
|
||||
releasesRespondWith([buildRelease({ body: null })]);
|
||||
await renderPanel();
|
||||
|
||||
expect(screen.queryByText('Show details')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AGH-010: expands and collapses the release notes', async () => {
|
||||
releasesRespondWith([buildRelease({ body: '- Fixed a bug' })]);
|
||||
const user = userEvent.setup();
|
||||
await renderPanel();
|
||||
|
||||
expect(screen.queryByText('Fixed a bug')).not.toBeInTheDocument();
|
||||
await user.click(screen.getByText('Show details'));
|
||||
expect(await screen.findByText('Fixed a bug')).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByText('Hide details'));
|
||||
await waitFor(() => expect(screen.queryByText('Fixed a bug')).not.toBeInTheDocument());
|
||||
expect(screen.getByText('Show details')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AGH-011: renders headings, list items and paragraphs from the markdown body', async () => {
|
||||
releasesRespondWith([
|
||||
buildRelease({
|
||||
body: '## Highlights\n- first item\n- second item\n\n### Details\nA plain paragraph.',
|
||||
}),
|
||||
]);
|
||||
const user = userEvent.setup();
|
||||
await renderPanel();
|
||||
await user.click(screen.getByText('Show details'));
|
||||
|
||||
expect((await screen.findByText('Highlights')).tagName).toBe('H3');
|
||||
expect(screen.getByText('Details').tagName).toBe('H4');
|
||||
expect(screen.getByText('first item').closest('li')).toBeInTheDocument();
|
||||
expect(screen.getByText('second item').closest('li')).toBeInTheDocument();
|
||||
expect(screen.getByText('A plain paragraph.').tagName).toBe('P');
|
||||
});
|
||||
|
||||
it('FE-MOB-AGH-012: renders bold and inline code inside list items', async () => {
|
||||
releasesRespondWith([buildRelease({ body: '- **bold text**\n- `inline code`' })]);
|
||||
const user = userEvent.setup();
|
||||
await renderPanel();
|
||||
await user.click(screen.getByText('Show details'));
|
||||
|
||||
expect((await screen.findByText('bold text')).tagName).toBe('STRONG');
|
||||
expect(screen.getByText('inline code').tagName).toBe('CODE');
|
||||
});
|
||||
|
||||
it('FE-MOB-AGH-013: keeps http links and rewrites unsafe link targets to #', async () => {
|
||||
releasesRespondWith([
|
||||
buildRelease({ body: '- [click here](https://example.com)\n- [evil](javascript:alert(1))' }),
|
||||
]);
|
||||
const user = userEvent.setup();
|
||||
await renderPanel();
|
||||
await user.click(screen.getByText('Show details'));
|
||||
|
||||
const safe = await screen.findByText('click here');
|
||||
expect(safe.tagName).toBe('A');
|
||||
expect(safe).toHaveAttribute('href', 'https://example.com');
|
||||
expect(safe).toHaveAttribute('rel', 'noopener noreferrer');
|
||||
expect(screen.getByText('evil')).toHaveAttribute('href', '#');
|
||||
});
|
||||
|
||||
it('FE-MOB-AGH-014: escapes html in the release body instead of rendering it', async () => {
|
||||
releasesRespondWith([buildRelease({ body: 'plain <img src=x onerror="alert(1)"> text' })]);
|
||||
const user = userEvent.setup();
|
||||
await renderPanel();
|
||||
await user.click(screen.getByText('Show details'));
|
||||
|
||||
expect(await screen.findByText('plain <img src=x onerror="alert(1)"> text')).toBeInTheDocument();
|
||||
expect(document.querySelector('img')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AGH-015: hides "Load more" when the first page is not full', async () => {
|
||||
releasesRespondWith(PAGE_2);
|
||||
await renderPanel();
|
||||
|
||||
expect(screen.getByText('v0.0.0')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Load more')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AGH-016: "Load more" appends the second page and then disappears', async () => {
|
||||
server.use(
|
||||
http.get('/api/admin/github-releases', ({ request }) => {
|
||||
const page = new URL(request.url).searchParams.get('page');
|
||||
return HttpResponse.json(page === '2' ? PAGE_2 : PAGE_1);
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
await renderPanel();
|
||||
|
||||
expect(screen.getAllByText(/^v1\.\d\.0$/)).toHaveLength(10);
|
||||
await user.click(screen.getByText('Load more'));
|
||||
|
||||
expect(await screen.findByText('v0.0.0')).toBeInTheDocument();
|
||||
expect(screen.getAllByText(/^v[01]\.\d\.0$/)).toHaveLength(13);
|
||||
expect(screen.queryByText('Load more')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AGH-017: a failing "Load more" swaps the timeline for the error card', async () => {
|
||||
let calls = 0;
|
||||
server.use(
|
||||
http.get('/api/admin/github-releases', () => {
|
||||
calls += 1;
|
||||
if (calls === 1) return HttpResponse.json(PAGE_1);
|
||||
return HttpResponse.json({ message: 'nope' }, { status: 500 });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
await renderPanel();
|
||||
|
||||
await user.click(screen.getByText('Load more'));
|
||||
await screen.findByText('Failed to load releases');
|
||||
});
|
||||
|
||||
it('FE-MOB-AGH-018: a non-array response is treated as an empty release list', async () => {
|
||||
releasesRespondWith({ message: 'rate limited' });
|
||||
await renderPanel();
|
||||
|
||||
expect(screen.getByText('Release History')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Load more')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Latest')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,293 @@
|
||||
// FE-MOB-MCPTOK-001 to FE-MOB-MCPTOK-014
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { render, screen, waitFor } from '../../../helpers/render';
|
||||
import { server } from '../../../helpers/msw/server';
|
||||
import { resetAllStores } from '../../../helpers/store';
|
||||
import { ToastContainer } from '../../../../src/components/shared/Toast';
|
||||
import MAdminMcpTokensPanel from '../../../../src/mobile/screens/admin/MAdminMcpTokensPanel';
|
||||
|
||||
const TOKEN_1 = {
|
||||
id: 1,
|
||||
name: 'CI Token',
|
||||
token_prefix: 'trek_abc',
|
||||
created_at: '2025-01-15T00:00:00Z',
|
||||
last_used_at: null,
|
||||
user_id: 10,
|
||||
username: 'alice',
|
||||
};
|
||||
|
||||
const TOKEN_2 = {
|
||||
id: 2,
|
||||
name: 'Ops Token',
|
||||
token_prefix: 'trek_xyz',
|
||||
created_at: '2025-03-01T00:00:00Z',
|
||||
last_used_at: '2025-04-01T00:00:00Z',
|
||||
user_id: 11,
|
||||
username: 'bob',
|
||||
};
|
||||
|
||||
function buildSession(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 1,
|
||||
client_id: 'cid',
|
||||
client_name: 'Claude Desktop',
|
||||
user_id: 10,
|
||||
username: 'alice',
|
||||
scopes: ['trips:read', 'budget:read'],
|
||||
access_token_expires_at: '2025-02-01T00:00:00Z',
|
||||
refresh_token_expires_at: '2025-03-01T00:00:00Z',
|
||||
created_at: '2025-01-01T00:00:00Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function renderPanel() {
|
||||
return render(
|
||||
<>
|
||||
<ToastContainer />
|
||||
<MAdminMcpTokensPanel />
|
||||
</>,
|
||||
);
|
||||
}
|
||||
|
||||
// The trash icons carry title="Delete" too — the confirm sheet's button is the
|
||||
// one without a title attribute.
|
||||
function confirmButton(label: string): HTMLElement {
|
||||
const candidates = screen.getAllByRole('button', { name: label });
|
||||
const withoutTitle = candidates.find((b) => !b.getAttribute('title'));
|
||||
return withoutTitle ?? candidates[candidates.length - 1];
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
describe('MAdminMcpTokensPanel', () => {
|
||||
it('FE-MOB-MCPTOK-001: renders the section header and both sub-section titles', async () => {
|
||||
renderPanel();
|
||||
|
||||
expect(screen.getByText('MCP Access')).toBeInTheDocument();
|
||||
expect(screen.getByText('Manage OAuth sessions and API tokens across all users')).toBeInTheDocument();
|
||||
expect(screen.getByText('OAuth Sessions')).toBeInTheDocument();
|
||||
expect(screen.getByText('API Tokens')).toBeInTheDocument();
|
||||
await screen.findByText('No MCP tokens have been created yet');
|
||||
});
|
||||
|
||||
it('FE-MOB-MCPTOK-002: shows spinners while both requests are in flight', async () => {
|
||||
server.use(
|
||||
http.get('/api/admin/mcp-tokens', async () => {
|
||||
await new Promise(() => {});
|
||||
return HttpResponse.json({ tokens: [] });
|
||||
}),
|
||||
http.get('/api/admin/oauth-sessions', async () => {
|
||||
await new Promise(() => {});
|
||||
return HttpResponse.json({ sessions: [] });
|
||||
}),
|
||||
);
|
||||
renderPanel();
|
||||
|
||||
expect(document.querySelectorAll('.animate-spin')).toHaveLength(2);
|
||||
expect(screen.queryByText('No MCP tokens have been created yet')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MCPTOK-003: renders both empty states when nothing is configured', async () => {
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('No active OAuth sessions');
|
||||
expect(screen.getByText('No MCP tokens have been created yet')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MCPTOK-004: token rows show name, prefix, owner and last-used date', async () => {
|
||||
server.use(http.get('/api/admin/mcp-tokens', () => HttpResponse.json({ tokens: [TOKEN_1, TOKEN_2] })));
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('CI Token');
|
||||
expect(screen.getByText('Ops Token')).toBeInTheDocument();
|
||||
expect(screen.getByText('alice')).toBeInTheDocument();
|
||||
expect(screen.getByText('bob')).toBeInTheDocument();
|
||||
expect(screen.getByText(/trek_abc/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/trek_xyz/)).toBeInTheDocument();
|
||||
// last_used_at null → "Never", otherwise the formatted date
|
||||
expect(screen.getByText('Never')).toBeInTheDocument();
|
||||
expect(screen.getByText('4/1/2025')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MCPTOK-005: session rows show client, user and scope chips', async () => {
|
||||
server.use(http.get('/api/admin/oauth-sessions', () => HttpResponse.json({ sessions: [buildSession()] })));
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('Claude Desktop');
|
||||
expect(screen.getByText('alice')).toBeInTheDocument();
|
||||
expect(screen.getByText('trips:read')).toBeInTheDocument();
|
||||
expect(screen.getByText('budget:read')).toBeInTheDocument();
|
||||
expect(screen.getByText('1/1/2025')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MCPTOK-006: scopes beyond the preview stay hidden until expanded', async () => {
|
||||
const user = userEvent.setup();
|
||||
const scopes = [
|
||||
'trips:read', 'trips:write', 'places:read', 'places:write',
|
||||
'budget:read', 'budget:write', 'packing:read',
|
||||
];
|
||||
server.use(
|
||||
http.get('/api/admin/oauth-sessions', () => HttpResponse.json({ sessions: [buildSession({ scopes })] })),
|
||||
);
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('Claude Desktop');
|
||||
expect(screen.queryByText('packing:read')).not.toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: '+1 more' }));
|
||||
expect(screen.getByText('packing:read')).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'show less' }));
|
||||
expect(screen.queryByText('packing:read')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MCPTOK-007: no expand button when scopes fit into the preview', async () => {
|
||||
server.use(
|
||||
http.get('/api/admin/oauth-sessions', () =>
|
||||
HttpResponse.json({ sessions: [buildSession({ scopes: ['trips:read'] })] }),
|
||||
),
|
||||
);
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('Claude Desktop');
|
||||
expect(screen.queryByText(/more$/)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('show less')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MCPTOK-008: token trash opens the delete confirm sheet', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(http.get('/api/admin/mcp-tokens', () => HttpResponse.json({ tokens: [TOKEN_1] })));
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('CI Token');
|
||||
await user.click(screen.getByRole('button', { name: 'Delete' }));
|
||||
|
||||
expect(screen.getByRole('dialog', { name: 'Delete Token' })).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText('This will revoke the token immediately. The user will lose MCP access through this token.'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MCPTOK-009: cancelling the confirm sheet keeps the token', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(http.get('/api/admin/mcp-tokens', () => HttpResponse.json({ tokens: [TOKEN_1] })));
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('CI Token');
|
||||
await user.click(screen.getByRole('button', { name: 'Delete' }));
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
|
||||
expect(screen.getByText('CI Token')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MCPTOK-010: confirming removes the token and toasts', async () => {
|
||||
const user = userEvent.setup();
|
||||
let deletedId = '';
|
||||
server.use(
|
||||
http.get('/api/admin/mcp-tokens', () => HttpResponse.json({ tokens: [TOKEN_1, TOKEN_2] })),
|
||||
http.delete('/api/admin/mcp-tokens/:id', ({ params }) => {
|
||||
deletedId = String(params.id);
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('CI Token');
|
||||
await user.click(screen.getAllByRole('button', { name: 'Delete' })[0]);
|
||||
await user.click(confirmButton('Delete'));
|
||||
|
||||
await waitFor(() => expect(screen.queryByText('CI Token')).not.toBeInTheDocument());
|
||||
expect(deletedId).toBe('1');
|
||||
expect(screen.getByText('Ops Token')).toBeInTheDocument();
|
||||
await screen.findByText('Token deleted');
|
||||
});
|
||||
|
||||
it('FE-MOB-MCPTOK-011: a failing delete keeps the token and shows the error toast', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.get('/api/admin/mcp-tokens', () => HttpResponse.json({ tokens: [TOKEN_1] })),
|
||||
http.delete('/api/admin/mcp-tokens/:id', () => HttpResponse.json({ error: 'nope' }, { status: 403 })),
|
||||
);
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('CI Token');
|
||||
await user.click(screen.getAllByRole('button', { name: 'Delete' })[0]);
|
||||
await user.click(confirmButton('Delete'));
|
||||
|
||||
await screen.findByText('Failed to delete token');
|
||||
expect(screen.getByText('CI Token')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MCPTOK-012: revoking a session removes it and toasts', async () => {
|
||||
const user = userEvent.setup();
|
||||
let revokedId = '';
|
||||
server.use(
|
||||
http.get('/api/admin/oauth-sessions', () =>
|
||||
HttpResponse.json({ sessions: [buildSession({ id: 5, client_name: 'Revoke Me' })] }),
|
||||
),
|
||||
http.delete('/api/admin/oauth-sessions/:id', ({ params }) => {
|
||||
revokedId = String(params.id);
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('Revoke Me');
|
||||
await user.click(screen.getAllByRole('button', { name: 'Delete' })[0]);
|
||||
expect(screen.getByRole('dialog', { name: 'Revoke Session' })).toBeInTheDocument();
|
||||
|
||||
// Cancelling leaves the session untouched; reopening still works.
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
|
||||
expect(revokedId).toBe('');
|
||||
|
||||
await user.click(screen.getAllByRole('button', { name: 'Delete' })[0]);
|
||||
await user.click(confirmButton('Delete'));
|
||||
|
||||
await waitFor(() => expect(screen.queryByText('Revoke Me')).not.toBeInTheDocument());
|
||||
expect(revokedId).toBe('5');
|
||||
await screen.findByText('Session revoked');
|
||||
});
|
||||
|
||||
it('FE-MOB-MCPTOK-013: a failing revoke keeps the session and shows the error toast', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.get('/api/admin/oauth-sessions', () =>
|
||||
HttpResponse.json({ sessions: [buildSession({ id: 6, client_name: 'Error Session' })] }),
|
||||
),
|
||||
http.delete('/api/admin/oauth-sessions/:id', () => HttpResponse.json({ error: 'nope' }, { status: 403 })),
|
||||
);
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('Error Session');
|
||||
await user.click(screen.getAllByRole('button', { name: 'Delete' })[0]);
|
||||
await user.click(confirmButton('Delete'));
|
||||
|
||||
await screen.findByText('Failed to revoke session');
|
||||
expect(screen.getByText('Error Session')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-MCPTOK-014: both load failures toast and fall back to the empty states', async () => {
|
||||
server.use(
|
||||
http.get('/api/admin/mcp-tokens', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
|
||||
http.get('/api/admin/oauth-sessions', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
|
||||
);
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('Failed to load tokens');
|
||||
expect(screen.getByText('Failed to load OAuth sessions')).toBeInTheDocument();
|
||||
expect(screen.getByText('No MCP tokens have been created yet')).toBeInTheDocument();
|
||||
expect(screen.getByText('No active OAuth sessions')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,540 @@
|
||||
// FE-MOB-ANOTIF-001 to FE-MOB-ANOTIF-031
|
||||
import { useState } from 'react';
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen, waitFor } from '../../../helpers/render';
|
||||
import { server } from '../../../helpers/msw/server';
|
||||
import { resetAllStores } from '../../../helpers/store';
|
||||
import { useTranslation } from '../../../../src/i18n';
|
||||
import type { useAdmin } from '../../../../src/pages/admin/useAdmin';
|
||||
import MAdminNotificationsSection from '../../../../src/mobile/screens/admin/MAdminNotificationsSection';
|
||||
|
||||
// The per-event matrix loads its own data and has its own spec — stub it so the
|
||||
// assertions here only see the section's own cards.
|
||||
vi.mock('../../../../src/mobile/screens/admin/MAdminNotifyMatrix', () => ({
|
||||
default: () => <div data-testid="notify-matrix" />,
|
||||
}));
|
||||
|
||||
const MASK = '••••••••';
|
||||
|
||||
interface HarnessProps {
|
||||
initial?: Record<string, string>;
|
||||
smtpLoaded?: boolean;
|
||||
toast?: { success: ReturnType<typeof vi.fn>; error: ReturnType<typeof vi.fn> };
|
||||
setTripRemindersEnabled?: (value: boolean) => void;
|
||||
}
|
||||
|
||||
function buildToast() {
|
||||
return { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() };
|
||||
}
|
||||
|
||||
// The section is a controlled child of useAdmin — this harness owns the same
|
||||
// smtpValues state so setSmtpValues updaters really re-render the card.
|
||||
function Harness({ initial = {}, smtpLoaded = true, toast = buildToast(), setTripRemindersEnabled = vi.fn() }: HarnessProps) {
|
||||
const { t } = useTranslation();
|
||||
const [smtpValues, setSmtpValues] = useState<Record<string, string>>(initial);
|
||||
const admin = {
|
||||
toast,
|
||||
smtpValues,
|
||||
setSmtpValues,
|
||||
smtpLoaded,
|
||||
setTripRemindersEnabled,
|
||||
} as unknown as ReturnType<typeof useAdmin>;
|
||||
return <MAdminNotificationsSection admin={admin} t={t} />;
|
||||
}
|
||||
|
||||
/** Records the body of every PUT /auth/app-settings the section sends. */
|
||||
function captureAppSettings() {
|
||||
const bodies: Record<string, unknown>[] = [];
|
||||
server.use(
|
||||
http.put('/api/auth/app-settings', async ({ request }) => {
|
||||
bodies.push((await request.json()) as Record<string, unknown>);
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
return bodies;
|
||||
}
|
||||
|
||||
function failAppSettings() {
|
||||
server.use(http.put('/api/auth/app-settings', () => HttpResponse.json({}, { status: 500 })));
|
||||
}
|
||||
|
||||
/** The two password inputs are, in DOM order, the SMTP password and the ntfy token. */
|
||||
function ntfyTokenInput() {
|
||||
return Array.from(document.querySelectorAll<HTMLInputElement>('input[type="password"]'))[1];
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
describe('MAdminNotificationsSection', () => {
|
||||
it('FE-MOB-ANOTIF-001: renders every channel card and prefills the SMTP fields', () => {
|
||||
render(
|
||||
<Harness
|
||||
initial={{ notification_channels: 'email', smtp_host: 'mail.test', smtp_port: '2525' }}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByText('Email (SMTP)')).toBeInTheDocument();
|
||||
expect(screen.getByText('Webhook')).toBeInTheDocument();
|
||||
expect(screen.getByText('Ntfy')).toBeInTheDocument();
|
||||
expect(screen.getByText('In-App')).toBeInTheDocument();
|
||||
expect(screen.getByText('Trip Reminders')).toBeInTheDocument();
|
||||
expect(screen.getByText('Admin Webhook')).toBeInTheDocument();
|
||||
expect(screen.getByText('Admin Ntfy')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('notify-matrix')).toBeInTheDocument();
|
||||
|
||||
expect(screen.getByPlaceholderText('mail.example.com')).toHaveValue('mail.test');
|
||||
expect(screen.getByPlaceholderText('587')).toHaveValue('2525');
|
||||
expect(screen.getByRole('switch', { name: 'Email (SMTP)' })).toHaveAttribute('aria-checked', 'true');
|
||||
expect(screen.getByRole('switch', { name: 'In-App' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-002: hides the credential fields until the settings have loaded', () => {
|
||||
render(<Harness smtpLoaded={false} initial={{ smtp_host: 'mail.test' }} />);
|
||||
|
||||
expect(screen.queryByPlaceholderText('mail.example.com')).not.toBeInTheDocument();
|
||||
expect(screen.queryByPlaceholderText('https://ntfy.sh')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('Email (SMTP)')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-003: derives the active channels from the plural setting', () => {
|
||||
render(<Harness initial={{ notification_channels: 'webhook,ntfy' }} />);
|
||||
|
||||
expect(screen.getByRole('switch', { name: 'Email (SMTP)' })).toHaveAttribute('aria-checked', 'false');
|
||||
expect(screen.getByRole('switch', { name: 'Webhook' })).toHaveAttribute('aria-checked', 'true');
|
||||
expect(screen.getByRole('switch', { name: 'Ntfy' })).toHaveAttribute('aria-checked', 'true');
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-004: falls back to the legacy singular setting', () => {
|
||||
render(<Harness initial={{ notification_channel: 'email' }} />);
|
||||
|
||||
expect(screen.getByRole('switch', { name: 'Email (SMTP)' })).toHaveAttribute('aria-checked', 'true');
|
||||
expect(screen.getByRole('switch', { name: 'Webhook' })).toHaveAttribute('aria-checked', 'false');
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-005: treats a missing setting as no active channel', () => {
|
||||
render(<Harness />);
|
||||
|
||||
expect(screen.getByRole('switch', { name: 'Email (SMTP)' })).toHaveAttribute('aria-checked', 'false');
|
||||
expect(screen.getByRole('switch', { name: 'Ntfy' })).toHaveAttribute('aria-checked', 'false');
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-006: enabling a channel saves the CSV and keeps unknown channel ids', async () => {
|
||||
const bodies = captureAppSettings();
|
||||
const user = userEvent.setup();
|
||||
render(<Harness initial={{ notification_channels: 'webhook,pushover' }} />);
|
||||
|
||||
await user.click(screen.getByRole('switch', { name: 'Email (SMTP)' }));
|
||||
|
||||
await waitFor(() => expect(bodies).toHaveLength(1));
|
||||
expect(bodies[0]).toEqual({ notification_channels: 'email,webhook,pushover' });
|
||||
expect(screen.getByRole('switch', { name: 'Email (SMTP)' })).toHaveAttribute('aria-checked', 'true');
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-007: disabling the last channel stores "none"', async () => {
|
||||
const bodies = captureAppSettings();
|
||||
const user = userEvent.setup();
|
||||
render(<Harness initial={{ notification_channels: 'ntfy' }} />);
|
||||
|
||||
await user.click(screen.getByRole('switch', { name: 'Ntfy' }));
|
||||
|
||||
await waitFor(() => expect(bodies).toHaveLength(1));
|
||||
expect(bodies[0]).toEqual({ notification_channels: 'none' });
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-008: a failed channel save rolls the toggle back and reports the error', async () => {
|
||||
failAppSettings();
|
||||
const toast = buildToast();
|
||||
const user = userEvent.setup();
|
||||
render(<Harness initial={{ notification_channels: 'email' }} toast={toast} />);
|
||||
|
||||
await user.click(screen.getByRole('switch', { name: 'Webhook' }));
|
||||
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Error'));
|
||||
expect(screen.getByRole('switch', { name: 'Webhook' })).toHaveAttribute('aria-checked', 'false');
|
||||
expect(screen.getByRole('switch', { name: 'Email (SMTP)' })).toHaveAttribute('aria-checked', 'true');
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-009: editing an SMTP field and saving sends only the credential keys', async () => {
|
||||
const bodies = captureAppSettings();
|
||||
const toast = buildToast();
|
||||
const setTripRemindersEnabled = vi.fn();
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.get('/api/auth/app-config', () => HttpResponse.json({ trip_reminders_enabled: true })),
|
||||
);
|
||||
render(
|
||||
<Harness
|
||||
initial={{ notification_channels: 'email', smtp_host: 'mail.test', admin_ntfy_topic: 'ops' }}
|
||||
toast={toast}
|
||||
setTripRemindersEnabled={setTripRemindersEnabled}
|
||||
/>,
|
||||
);
|
||||
|
||||
// smtp_user and smtp_from share a placeholder — the first one is the user field
|
||||
await user.type(screen.getAllByPlaceholderText('trek@example.com')[0], 'bot');
|
||||
await user.click(screen.getAllByRole('button', { name: 'Save' })[0]);
|
||||
|
||||
await waitFor(() => expect(bodies).toHaveLength(1));
|
||||
expect(bodies[0]).toEqual({ smtp_host: 'mail.test', smtp_user: 'bot' });
|
||||
expect(toast.success).toHaveBeenCalledWith('Notification settings saved');
|
||||
// The follow-up app-config read syncs the reminder flag back into the store
|
||||
await waitFor(() => expect(setTripRemindersEnabled).toHaveBeenCalledWith(true));
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-010: a failed SMTP save reports the error', async () => {
|
||||
failAppSettings();
|
||||
const toast = buildToast();
|
||||
const user = userEvent.setup();
|
||||
render(<Harness initial={{ smtp_host: 'mail.test' }} toast={toast} />);
|
||||
|
||||
await user.click(screen.getAllByRole('button', { name: 'Save' })[0]);
|
||||
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Error'));
|
||||
expect(toast.success).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-011: the TLS toggle flips smtp_skip_tls_verify', async () => {
|
||||
const bodies = captureAppSettings();
|
||||
const user = userEvent.setup();
|
||||
render(<Harness initial={{ notification_channels: 'email', smtp_host: 'mail.test' }} />);
|
||||
|
||||
const tls = screen.getByRole('switch', { name: 'Skip TLS certificate check' });
|
||||
expect(tls).toHaveAttribute('aria-checked', 'false');
|
||||
await user.click(tls);
|
||||
expect(tls).toHaveAttribute('aria-checked', 'true');
|
||||
|
||||
await user.click(screen.getAllByRole('button', { name: 'Save' })[0]);
|
||||
await waitFor(() => expect(bodies).toHaveLength(1));
|
||||
expect(bodies[0]).toMatchObject({ smtp_skip_tls_verify: 'true' });
|
||||
|
||||
await user.click(tls);
|
||||
expect(tls).toHaveAttribute('aria-checked', 'false');
|
||||
await user.click(screen.getAllByRole('button', { name: 'Save' })[0]);
|
||||
await waitFor(() => expect(bodies).toHaveLength(2));
|
||||
expect(bodies[1]).toMatchObject({ smtp_skip_tls_verify: 'false' });
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-012: the test button is disabled until a host is configured', () => {
|
||||
render(<Harness initial={{ smtp_host: ' ' }} />);
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Send test email' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-013: the SMTP test persists the credentials first and reports success', async () => {
|
||||
const bodies = captureAppSettings();
|
||||
const toast = buildToast();
|
||||
const user = userEvent.setup();
|
||||
server.use(http.post('/api/notifications/test-smtp', () => HttpResponse.json({ success: true })));
|
||||
render(<Harness initial={{ smtp_host: 'mail.test', smtp_from: 'trek@test' }} toast={toast} />);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Send test email' }));
|
||||
|
||||
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Test email sent successfully'));
|
||||
expect(bodies[0]).toEqual({ smtp_host: 'mail.test', smtp_from: 'trek@test' });
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-014: an unsuccessful SMTP test surfaces the server error text', async () => {
|
||||
const toast = buildToast();
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.post('/api/notifications/test-smtp', () =>
|
||||
HttpResponse.json({ success: false, error: 'auth rejected' }),
|
||||
),
|
||||
);
|
||||
render(<Harness initial={{ smtp_host: 'mail.test' }} toast={toast} />);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Send test email' }));
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('auth rejected'));
|
||||
|
||||
// Without an error field the generic message is used
|
||||
server.use(http.post('/api/notifications/test-smtp', () => HttpResponse.json({ success: false })));
|
||||
await user.click(screen.getByRole('button', { name: 'Send test email' }));
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Test email failed'));
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-015: a rejected SMTP test falls back to the generic failure text', async () => {
|
||||
const toast = buildToast();
|
||||
const user = userEvent.setup();
|
||||
server.use(http.post('/api/notifications/test-smtp', () => HttpResponse.json({}, { status: 500 })));
|
||||
render(<Harness initial={{ smtp_host: 'mail.test' }} toast={toast} />);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Send test email' }));
|
||||
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Test email failed'));
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-016: trip reminders default to on and can be switched off', async () => {
|
||||
const bodies = captureAppSettings();
|
||||
const toast = buildToast();
|
||||
const setTripRemindersEnabled = vi.fn();
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.get('/api/auth/app-config', () => HttpResponse.json({ trip_reminders_enabled: false })),
|
||||
);
|
||||
render(<Harness toast={toast} setTripRemindersEnabled={setTripRemindersEnabled} />);
|
||||
|
||||
const toggle = screen.getByRole('switch', { name: 'Trip Reminders' });
|
||||
expect(toggle).toHaveAttribute('aria-checked', 'true');
|
||||
await user.click(toggle);
|
||||
|
||||
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Trip reminders disabled'));
|
||||
expect(bodies[0]).toEqual({ notify_trip_reminder: 'false' });
|
||||
expect(toggle).toHaveAttribute('aria-checked', 'false');
|
||||
await waitFor(() => expect(setTripRemindersEnabled).toHaveBeenCalledWith(false));
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-017: switching trip reminders back on reports the enabled toast', async () => {
|
||||
const bodies = captureAppSettings();
|
||||
const toast = buildToast();
|
||||
const user = userEvent.setup();
|
||||
render(<Harness initial={{ notify_trip_reminder: 'false' }} toast={toast} />);
|
||||
|
||||
await user.click(screen.getByRole('switch', { name: 'Trip Reminders' }));
|
||||
|
||||
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Trip reminders enabled'));
|
||||
expect(bodies[0]).toEqual({ notify_trip_reminder: 'true' });
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-018: a failed trip reminder save rolls the toggle back', async () => {
|
||||
failAppSettings();
|
||||
const toast = buildToast();
|
||||
const user = userEvent.setup();
|
||||
render(<Harness toast={toast} />);
|
||||
|
||||
await user.click(screen.getByRole('switch', { name: 'Trip Reminders' }));
|
||||
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Error'));
|
||||
expect(screen.getByRole('switch', { name: 'Trip Reminders' })).toHaveAttribute('aria-checked', 'true');
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-019: the admin webhook URL is saved and tested', async () => {
|
||||
const bodies = captureAppSettings();
|
||||
const toast = buildToast();
|
||||
const user = userEvent.setup();
|
||||
let testedUrl: string | undefined;
|
||||
server.use(
|
||||
http.post('/api/notifications/test-webhook', async ({ request }) => {
|
||||
testedUrl = ((await request.json()) as { url?: string }).url;
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
render(<Harness toast={toast} />);
|
||||
|
||||
const input = screen.getByPlaceholderText('https://discord.com/api/webhooks/...');
|
||||
await user.type(input, 'https://hooks.test/abc');
|
||||
await user.click(screen.getAllByRole('button', { name: 'Save' })[1]);
|
||||
|
||||
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Admin webhook URL saved'));
|
||||
expect(bodies[0]).toEqual({ admin_webhook_url: 'https://hooks.test/abc' });
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Send test webhook' }));
|
||||
await waitFor(() => expect(testedUrl).toBe('https://hooks.test/abc'));
|
||||
expect(toast.success).toHaveBeenCalledWith('Test webhook sent successfully');
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-020: a masked admin webhook is tested without resending the URL', async () => {
|
||||
const bodies = captureAppSettings();
|
||||
const toast = buildToast();
|
||||
const user = userEvent.setup();
|
||||
let payload: { url?: string } | undefined;
|
||||
server.use(
|
||||
http.post('/api/notifications/test-webhook', async ({ request }) => {
|
||||
payload = (await request.json()) as { url?: string };
|
||||
return HttpResponse.json({ success: false, error: 'endpoint gone' });
|
||||
}),
|
||||
);
|
||||
render(<Harness initial={{ admin_webhook_url: MASK }} toast={toast} />);
|
||||
|
||||
// The masked value is never echoed into the input, only into the placeholder
|
||||
const maskedInput = screen
|
||||
.getAllByPlaceholderText(MASK)
|
||||
.find((el) => (el as HTMLInputElement).type === 'text')!;
|
||||
expect(maskedInput).toHaveValue('');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Send test webhook' }));
|
||||
await waitFor(() => expect(payload).toBeDefined());
|
||||
// The mask is not a URL, so nothing is re-saved before the probe
|
||||
expect(payload).toEqual({});
|
||||
expect(bodies).toHaveLength(0);
|
||||
expect(toast.error).toHaveBeenCalledWith('endpoint gone');
|
||||
|
||||
server.use(http.post('/api/notifications/test-webhook', () => HttpResponse.json({ success: false })));
|
||||
await user.click(screen.getByRole('button', { name: 'Send test webhook' }));
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Test webhook failed'));
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-021: admin webhook errors are reported for save and test alike', async () => {
|
||||
const toast = buildToast();
|
||||
const user = userEvent.setup();
|
||||
failAppSettings();
|
||||
server.use(
|
||||
http.post('/api/notifications/test-webhook', () => HttpResponse.json({}, { status: 500 })),
|
||||
);
|
||||
render(<Harness initial={{ admin_webhook_url: 'https://hooks.test/abc' }} toast={toast} />);
|
||||
|
||||
await user.click(screen.getAllByRole('button', { name: 'Save' })[1]);
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Error'));
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Send test webhook' }));
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Test webhook failed'));
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-022: the admin webhook test button is disabled without a URL', () => {
|
||||
render(<Harness />);
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Send test webhook' })).toBeDisabled();
|
||||
expect(screen.getByRole('button', { name: 'Send test ntfy' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-023: saving admin ntfy sends server, topic and a freshly typed token', async () => {
|
||||
const bodies = captureAppSettings();
|
||||
const toast = buildToast();
|
||||
const user = userEvent.setup();
|
||||
render(<Harness toast={toast} />);
|
||||
|
||||
await user.type(screen.getByPlaceholderText('https://ntfy.sh'), 'https://ntfy.test');
|
||||
await user.type(screen.getByPlaceholderText('trek-admin-alerts'), 'ops');
|
||||
await user.type(ntfyTokenInput(), 'tk_1');
|
||||
await user.click(screen.getAllByRole('button', { name: 'Save' })[2]);
|
||||
|
||||
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Admin ntfy settings saved'));
|
||||
expect(bodies[0]).toEqual({
|
||||
admin_ntfy_server: 'https://ntfy.test',
|
||||
admin_ntfy_topic: 'ops',
|
||||
admin_ntfy_token: 'tk_1',
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-024: a masked ntfy token is omitted from the save payload', async () => {
|
||||
const bodies = captureAppSettings();
|
||||
const user = userEvent.setup();
|
||||
render(<Harness initial={{ admin_ntfy_topic: 'ops', admin_ntfy_token: MASK }} />);
|
||||
|
||||
await user.click(screen.getAllByRole('button', { name: 'Save' })[2]);
|
||||
|
||||
await waitFor(() => expect(bodies).toHaveLength(1));
|
||||
expect(bodies[0]).toEqual({ admin_ntfy_server: '', admin_ntfy_topic: 'ops' });
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-025: a failed ntfy save reports the error', async () => {
|
||||
failAppSettings();
|
||||
const toast = buildToast();
|
||||
const user = userEvent.setup();
|
||||
render(<Harness initial={{ admin_ntfy_topic: 'ops' }} toast={toast} />);
|
||||
|
||||
await user.click(screen.getAllByRole('button', { name: 'Save' })[2]);
|
||||
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Error'));
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-026: the ntfy test sends topic, server and the unmasked token', async () => {
|
||||
const toast = buildToast();
|
||||
const user = userEvent.setup();
|
||||
let payload: Record<string, unknown> | undefined;
|
||||
server.use(
|
||||
http.post('/api/notifications/test-ntfy', async ({ request }) => {
|
||||
payload = (await request.json()) as Record<string, unknown>;
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
render(
|
||||
<Harness
|
||||
initial={{ admin_ntfy_topic: ' ops ', admin_ntfy_server: 'https://ntfy.test', admin_ntfy_token: 'tk_1' }}
|
||||
toast={toast}
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Send test ntfy' }));
|
||||
|
||||
await waitFor(() => expect(payload).toBeDefined());
|
||||
expect(payload).toEqual({ topic: 'ops', server: 'https://ntfy.test', token: 'tk_1' });
|
||||
expect(toast.success).toHaveBeenCalledWith('Test ntfy sent successfully');
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-027: a masked token is sent as null and a failed test is reported', async () => {
|
||||
const toast = buildToast();
|
||||
const user = userEvent.setup();
|
||||
let payload: Record<string, unknown> | undefined;
|
||||
server.use(
|
||||
http.post('/api/notifications/test-ntfy', async ({ request }) => {
|
||||
payload = (await request.json()) as Record<string, unknown>;
|
||||
return HttpResponse.json({ success: false, error: 'topic refused' });
|
||||
}),
|
||||
);
|
||||
render(<Harness initial={{ admin_ntfy_topic: 'ops', admin_ntfy_token: MASK }} toast={toast} />);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Send test ntfy' }));
|
||||
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('topic refused'));
|
||||
expect(payload).toEqual({ topic: 'ops', server: null, token: null });
|
||||
|
||||
server.use(http.post('/api/notifications/test-ntfy', () => HttpResponse.json({ success: false })));
|
||||
await user.click(screen.getByRole('button', { name: 'Send test ntfy' }));
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Test ntfy failed'));
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-028: a rejected ntfy test falls back to the generic failure text', async () => {
|
||||
const toast = buildToast();
|
||||
const user = userEvent.setup();
|
||||
server.use(http.post('/api/notifications/test-ntfy', () => HttpResponse.json({}, { status: 500 })));
|
||||
render(<Harness initial={{ admin_ntfy_topic: 'ops' }} toast={toast} />);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Send test ntfy' }));
|
||||
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Test ntfy failed'));
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-029: the Clear button only exists for a stored token and wipes it', async () => {
|
||||
const bodies = captureAppSettings();
|
||||
const toast = buildToast();
|
||||
const user = userEvent.setup();
|
||||
render(<Harness initial={{ admin_ntfy_token: MASK }} toast={toast} />);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Clear' }));
|
||||
|
||||
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Admin access token cleared'));
|
||||
expect(bodies[0]).toEqual({ admin_ntfy_token: '' });
|
||||
await waitFor(() => expect(screen.queryByRole('button', { name: 'Clear' })).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-030: a failed token clear keeps the button and reports the error', async () => {
|
||||
failAppSettings();
|
||||
const toast = buildToast();
|
||||
const user = userEvent.setup();
|
||||
render(<Harness initial={{ admin_ntfy_token: MASK }} toast={toast} />);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Clear' }));
|
||||
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Error'));
|
||||
expect(screen.getByRole('button', { name: 'Clear' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ANOTIF-031: a failing app-config refresh does not break the SMTP save', async () => {
|
||||
const toast = buildToast();
|
||||
const setTripRemindersEnabled = vi.fn();
|
||||
const user = userEvent.setup();
|
||||
captureAppSettings();
|
||||
server.use(http.get('/api/auth/app-config', () => HttpResponse.json({}, { status: 500 })));
|
||||
render(
|
||||
<Harness
|
||||
initial={{ smtp_host: 'mail.test' }}
|
||||
toast={toast}
|
||||
setTripRemindersEnabled={setTripRemindersEnabled}
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.click(screen.getAllByRole('button', { name: 'Save' })[0]);
|
||||
|
||||
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Notification settings saved'));
|
||||
expect(setTripRemindersEnabled).not.toHaveBeenCalled();
|
||||
expect(toast.error).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,204 @@
|
||||
// FE-MOB-AMATRIX-001 to FE-MOB-AMATRIX-011
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen, waitFor } from '../../../helpers/render';
|
||||
import { server } from '../../../helpers/msw/server';
|
||||
import { resetAllStores } from '../../../helpers/store';
|
||||
import { useTranslation } from '../../../../src/i18n';
|
||||
import type { useToast } from '../../../../src/components/shared/Toast';
|
||||
import MAdminNotifyMatrix from '../../../../src/mobile/screens/admin/MAdminNotifyMatrix';
|
||||
|
||||
const MATRIX = {
|
||||
event_types: ['version_available', 'trip_reminder'],
|
||||
channels: [
|
||||
{ id: 'inapp', active: true },
|
||||
{ id: 'email', active: true },
|
||||
{ id: 'webhook', active: false },
|
||||
{ id: 'ntfy', active: true },
|
||||
],
|
||||
implemented_combos: {
|
||||
version_available: ['inapp', 'email'],
|
||||
trip_reminder: ['inapp'],
|
||||
},
|
||||
preferences: {
|
||||
version_available: { inapp: true, email: false },
|
||||
},
|
||||
};
|
||||
|
||||
function buildToast() {
|
||||
return {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
function Harness({ toast }: { toast: ReturnType<typeof useToast> }) {
|
||||
const { t } = useTranslation();
|
||||
return <MAdminNotifyMatrix t={t} toast={toast} />;
|
||||
}
|
||||
|
||||
function matrixRespondsWith(payload: unknown) {
|
||||
server.use(http.get('/api/admin/notification-preferences', () => HttpResponse.json(payload)));
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
describe('MAdminNotifyMatrix', () => {
|
||||
it('FE-MOB-AMATRIX-001: shows the loading card until the matrix arrives', async () => {
|
||||
server.use(
|
||||
http.get('/api/admin/notification-preferences', async () => {
|
||||
await new Promise(() => {});
|
||||
return HttpResponse.json(MATRIX);
|
||||
}),
|
||||
);
|
||||
render(<Harness toast={buildToast()} />);
|
||||
|
||||
expect(screen.getByText('Loading...')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AMATRIX-002: stays on the loading card when the request fails', async () => {
|
||||
server.use(
|
||||
http.get('/api/admin/notification-preferences', () => HttpResponse.json({}, { status: 500 })),
|
||||
);
|
||||
render(<Harness toast={buildToast()} />);
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Loading...')).toBeInTheDocument());
|
||||
expect(screen.queryByRole('switch')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AMATRIX-003: shows the empty hint when the server reports no event types', async () => {
|
||||
matrixRespondsWith({ event_types: [], implemented_combos: {}, preferences: {} });
|
||||
render(<Harness toast={buildToast()} />);
|
||||
|
||||
expect(
|
||||
await screen.findByText(
|
||||
'No notification channels are configured. Ask an admin to set up email or webhook notifications.',
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AMATRIX-004: renders only channels that are active and implemented somewhere', async () => {
|
||||
matrixRespondsWith(MATRIX);
|
||||
render(<Harness toast={buildToast()} />);
|
||||
|
||||
await screen.findByText('New version available');
|
||||
expect(screen.getByText('In-App')).toBeInTheDocument();
|
||||
expect(screen.getByText('Email')).toBeInTheDocument();
|
||||
// webhook is inactive, ntfy is active but not implemented for any event
|
||||
expect(screen.queryByText('Webhook')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Ntfy')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AMATRIX-005: falls back to the raw event id when no label key exists', async () => {
|
||||
matrixRespondsWith(MATRIX);
|
||||
render(<Harness toast={buildToast()} />);
|
||||
|
||||
expect(await screen.findByText('trip_reminder')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AMATRIX-006: reflects stored preferences and defaults missing ones to on', async () => {
|
||||
matrixRespondsWith(MATRIX);
|
||||
render(<Harness toast={buildToast()} />);
|
||||
|
||||
const versionInapp = await screen.findByRole('switch', { name: 'version_available inapp' });
|
||||
expect(versionInapp).toHaveAttribute('aria-checked', 'true');
|
||||
expect(screen.getByRole('switch', { name: 'version_available email' })).toHaveAttribute(
|
||||
'aria-checked',
|
||||
'false',
|
||||
);
|
||||
// trip_reminder has no stored preference at all
|
||||
expect(screen.getByRole('switch', { name: 'trip_reminder inapp' })).toHaveAttribute('aria-checked', 'true');
|
||||
});
|
||||
|
||||
it('FE-MOB-AMATRIX-007: renders a dash for combos the backend does not implement', async () => {
|
||||
matrixRespondsWith(MATRIX);
|
||||
render(<Harness toast={buildToast()} />);
|
||||
|
||||
await screen.findByText('trip_reminder');
|
||||
expect(screen.queryByRole('switch', { name: 'trip_reminder email' })).not.toBeInTheDocument();
|
||||
expect(screen.getByText('—')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AMATRIX-008: toggling a cell persists the whole preference map', async () => {
|
||||
matrixRespondsWith(MATRIX);
|
||||
let body: Record<string, Record<string, boolean>> | undefined;
|
||||
server.use(
|
||||
http.put('/api/admin/notification-preferences', async ({ request }) => {
|
||||
body = (await request.json()) as Record<string, Record<string, boolean>>;
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<Harness toast={buildToast()} />);
|
||||
|
||||
await user.click(await screen.findByRole('switch', { name: 'version_available email' }));
|
||||
|
||||
await waitFor(() => expect(body).toBeDefined());
|
||||
expect(body).toEqual({ version_available: { inapp: true, email: true } });
|
||||
expect(screen.getByRole('switch', { name: 'version_available email' })).toHaveAttribute(
|
||||
'aria-checked',
|
||||
'true',
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-MOB-AMATRIX-009: a failed save reverts the toggle and reports the error', async () => {
|
||||
matrixRespondsWith(MATRIX);
|
||||
server.use(
|
||||
http.put('/api/admin/notification-preferences', () => HttpResponse.json({}, { status: 500 })),
|
||||
);
|
||||
const toast = buildToast();
|
||||
const user = userEvent.setup();
|
||||
render(<Harness toast={toast} />);
|
||||
|
||||
await user.click(await screen.findByRole('switch', { name: 'version_available inapp' }));
|
||||
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Error'));
|
||||
expect(screen.getByRole('switch', { name: 'version_available inapp' })).toHaveAttribute(
|
||||
'aria-checked',
|
||||
'true',
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-MOB-AMATRIX-010: toggling an event without stored preferences seeds it from the default', async () => {
|
||||
matrixRespondsWith(MATRIX);
|
||||
let body: Record<string, Record<string, boolean>> | undefined;
|
||||
server.use(
|
||||
http.put('/api/admin/notification-preferences', async ({ request }) => {
|
||||
body = (await request.json()) as Record<string, Record<string, boolean>>;
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<Harness toast={buildToast()} />);
|
||||
|
||||
await user.click(await screen.findByRole('switch', { name: 'trip_reminder inapp' }));
|
||||
|
||||
await waitFor(() => expect(body).toBeDefined());
|
||||
expect(body).toEqual({
|
||||
version_available: { inapp: true, email: false },
|
||||
trip_reminder: { inapp: false },
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-MOB-AMATRIX-011: a response without a channel list renders the events but no toggles', async () => {
|
||||
matrixRespondsWith({
|
||||
event_types: ['version_available'],
|
||||
implemented_combos: { version_available: ['inapp'] },
|
||||
preferences: {},
|
||||
});
|
||||
render(<Harness toast={buildToast()} />);
|
||||
|
||||
expect(await screen.findByText('New version available')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('switch')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('In-App')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,677 @@
|
||||
// FE-MOB-APKG-001 to FE-MOB-APKG-028
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { render, screen, fireEvent, waitFor, within } from '../../../helpers/render';
|
||||
import { server } from '../../../helpers/msw/server';
|
||||
import { resetAllStores } from '../../../helpers/store';
|
||||
import { ToastContainer } from '../../../../src/components/shared/Toast';
|
||||
import MAdminPackingTemplateManager from '../../../../src/mobile/screens/admin/MAdminPackingTemplateManager';
|
||||
|
||||
const tmpl1 = { id: 1, name: 'Beach Trip', item_count: 5, category_count: 2, created_by_name: 'admin' };
|
||||
const tmpl2 = { id: 2, name: 'City Break', item_count: 3, category_count: 1, created_by_name: 'admin' };
|
||||
|
||||
const cat1 = { id: 10, template_id: 1, name: 'Clothing', sort_order: 0 };
|
||||
const item1 = { id: 100, category_id: 10, name: 'T-shirt', sort_order: 0 };
|
||||
const item2 = { id: 101, category_id: 10, name: 'Shorts', sort_order: 1 };
|
||||
|
||||
function list(templates: unknown[]) {
|
||||
return http.get('/api/admin/packing-templates', () => HttpResponse.json({ templates }));
|
||||
}
|
||||
|
||||
function detail(id: number, categories: unknown[], items: unknown[]) {
|
||||
return http.get(`/api/admin/packing-templates/${id}`, () => HttpResponse.json({ categories, items }));
|
||||
}
|
||||
|
||||
function renderManager() {
|
||||
return render(<><ToastContainer /><MAdminPackingTemplateManager /></>);
|
||||
}
|
||||
|
||||
// Template rows nest the name two levels below the row that holds the icon buttons.
|
||||
function templateRow(name: string): HTMLElement {
|
||||
return screen.getByText(name).parentElement!.parentElement as HTMLElement;
|
||||
}
|
||||
|
||||
function categoryHeader(name: string): HTMLElement {
|
||||
return screen.getByText(name).closest('div') as HTMLElement;
|
||||
}
|
||||
|
||||
function itemRow(name: string): HTMLElement {
|
||||
return screen.getByText(name).closest('div') as HTMLElement;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
});
|
||||
|
||||
describe('MAdminPackingTemplateManager', () => {
|
||||
it('FE-MOB-APKG-001: shows the spinner while templates load, then the empty state', async () => {
|
||||
server.use(
|
||||
http.get('/api/admin/packing-templates', async () => {
|
||||
await new Promise(r => setTimeout(r, 60));
|
||||
return HttpResponse.json({ templates: [] });
|
||||
}),
|
||||
);
|
||||
renderManager();
|
||||
|
||||
expect(document.querySelector('.animate-spin')).toBeInTheDocument();
|
||||
expect(screen.getByText('Packing Templates')).toBeInTheDocument();
|
||||
expect(screen.getByText('Create reusable packing lists for your trips')).toBeInTheDocument();
|
||||
|
||||
await screen.findByText('No templates created yet');
|
||||
expect(document.querySelector('.animate-spin')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-002: renders each template with its category and item counts', async () => {
|
||||
server.use(list([tmpl1, tmpl2]));
|
||||
renderManager();
|
||||
|
||||
await screen.findByText('Beach Trip');
|
||||
expect(screen.getByText('City Break')).toBeInTheDocument();
|
||||
expect(screen.getByText('2 categories · 5 items')).toBeInTheDocument();
|
||||
expect(screen.getByText('1 categories · 3 items')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-003: a failing list request surfaces the load error toast', async () => {
|
||||
server.use(http.get('/api/admin/packing-templates', () => HttpResponse.error()));
|
||||
renderManager();
|
||||
|
||||
await screen.findByText('Failed to load templates');
|
||||
expect(screen.getByText('No templates created yet')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-004: creating a template prepends it, expands it and toasts', async () => {
|
||||
const user = userEvent.setup();
|
||||
let posted: unknown = null;
|
||||
server.use(
|
||||
list([tmpl1]),
|
||||
http.post('/api/admin/packing-templates', async ({ request }) => {
|
||||
posted = await request.json();
|
||||
return HttpResponse.json({ template: { id: 99, name: 'Winter Trip' } });
|
||||
}),
|
||||
detail(99, [], []),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'New Template' }));
|
||||
await user.type(screen.getByPlaceholderText('Template name (e.g. Beach Holiday)'), ' Winter Trip {Enter}');
|
||||
|
||||
await waitFor(() => expect(posted).toEqual({ name: 'Winter Trip' }));
|
||||
await screen.findByText('Template created');
|
||||
expect(screen.getByText('0 categories · 0 items')).toBeInTheDocument();
|
||||
// The new template is expanded right away, so its category editor is visible.
|
||||
expect(screen.getByRole('button', { name: 'Add category' })).toBeInTheDocument();
|
||||
expect(screen.queryByPlaceholderText('Template name (e.g. Beach Holiday)')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-005: saving a blank template name is a no-op', async () => {
|
||||
const user = userEvent.setup();
|
||||
let postCalls = 0;
|
||||
server.use(
|
||||
http.post('/api/admin/packing-templates', () => {
|
||||
postCalls += 1;
|
||||
return HttpResponse.json({ template: { id: 5, name: '' } });
|
||||
}),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('No templates created yet');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'New Template' }));
|
||||
await user.type(screen.getByPlaceholderText('Template name (e.g. Beach Holiday)'), ' ');
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
|
||||
expect(postCalls).toBe(0);
|
||||
expect(screen.getByPlaceholderText('Template name (e.g. Beach Holiday)')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-006: a failing create shows the create error toast', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.post('/api/admin/packing-templates', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('No templates created yet');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'New Template' }));
|
||||
await user.type(screen.getByPlaceholderText('Template name (e.g. Beach Holiday)'), 'Boom{Enter}');
|
||||
|
||||
await screen.findByText('Failed to create template');
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-007: Escape and the cancel button both close the create field', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderManager();
|
||||
await screen.findByText('No templates created yet');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'New Template' }));
|
||||
await user.type(screen.getByPlaceholderText('Template name (e.g. Beach Holiday)'), 'Draft{Escape}');
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByPlaceholderText('Template name (e.g. Beach Holiday)')).not.toBeInTheDocument(),
|
||||
);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'New Template' }));
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByPlaceholderText('Template name (e.g. Beach Holiday)')).not.toBeInTheDocument(),
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-008: expanding loads categories and items, collapsing hides them again', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(list([tmpl1]), detail(1, [cat1], [item1, item2]));
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Expand' }));
|
||||
await screen.findByText('Clothing');
|
||||
expect(screen.getByText('T-shirt')).toBeInTheDocument();
|
||||
expect(screen.getByText('Shorts')).toBeInTheDocument();
|
||||
// The category header counts its items.
|
||||
expect(within(categoryHeader('Clothing')).getByText('2')).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Collapse' }));
|
||||
await waitFor(() => expect(screen.queryByText('Clothing')).not.toBeInTheDocument());
|
||||
expect(screen.queryByText('T-shirt')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-009: a failing detail request toasts and leaves the template empty', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
list([tmpl1]),
|
||||
http.get('/api/admin/packing-templates/1', () => HttpResponse.error()),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
|
||||
await user.click(screen.getByText('Beach Trip'));
|
||||
|
||||
await screen.findByText('Failed to load templates');
|
||||
expect(screen.getByRole('button', { name: 'Add category' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-010: deleting a template removes it and collapses the expanded panel', async () => {
|
||||
const user = userEvent.setup();
|
||||
let deleted = false;
|
||||
server.use(
|
||||
list([tmpl1, tmpl2]),
|
||||
detail(1, [cat1], [item1]),
|
||||
http.delete('/api/admin/packing-templates/1', () => {
|
||||
deleted = true;
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
await user.click(screen.getByText('Beach Trip'));
|
||||
await screen.findByText('Clothing');
|
||||
|
||||
await user.click(within(templateRow('Beach Trip')).getByRole('button', { name: 'Delete' }));
|
||||
|
||||
await waitFor(() => expect(deleted).toBe(true));
|
||||
await waitFor(() => expect(screen.queryByText('Beach Trip')).not.toBeInTheDocument());
|
||||
expect(screen.queryByText('Clothing')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('City Break')).toBeInTheDocument();
|
||||
await screen.findByText('Template deleted');
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-011: a failing template delete keeps the row and toasts', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
list([tmpl1]),
|
||||
http.delete('/api/admin/packing-templates/1', () => HttpResponse.error()),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
|
||||
await user.click(within(templateRow('Beach Trip')).getByRole('button', { name: 'Delete' }));
|
||||
|
||||
await screen.findByText('Failed to delete template');
|
||||
expect(screen.getByText('Beach Trip')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-012: renaming a template persists the trimmed name', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: unknown = null;
|
||||
server.use(
|
||||
list([tmpl1]),
|
||||
http.put('/api/admin/packing-templates/1', async ({ request }) => {
|
||||
body = await request.json();
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
|
||||
await user.click(within(templateRow('Beach Trip')).getByRole('button', { name: 'Edit' }));
|
||||
const input = screen.getByDisplayValue('Beach Trip');
|
||||
await user.clear(input);
|
||||
await user.type(input, 'Summer Packing{Enter}');
|
||||
|
||||
await waitFor(() => expect(body).toEqual({ name: 'Summer Packing' }));
|
||||
await screen.findByText('Summer Packing');
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-013: blurring an emptied template name cancels the rename', async () => {
|
||||
const user = userEvent.setup();
|
||||
let putCalls = 0;
|
||||
server.use(
|
||||
list([tmpl1]),
|
||||
http.put('/api/admin/packing-templates/1', () => {
|
||||
putCalls += 1;
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
|
||||
await user.click(within(templateRow('Beach Trip')).getByRole('button', { name: 'Edit' }));
|
||||
const input = screen.getByDisplayValue('Beach Trip');
|
||||
await user.clear(input);
|
||||
fireEvent.blur(input);
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Beach Trip')).toBeInTheDocument());
|
||||
expect(putCalls).toBe(0);
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-014: Escape cancels the rename and a failing rename toasts', async () => {
|
||||
const user = userEvent.setup();
|
||||
let putCalls = 0;
|
||||
server.use(
|
||||
list([tmpl1]),
|
||||
http.put('/api/admin/packing-templates/1', () => {
|
||||
putCalls += 1;
|
||||
return HttpResponse.error();
|
||||
}),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
|
||||
await user.click(within(templateRow('Beach Trip')).getByRole('button', { name: 'Edit' }));
|
||||
await user.type(screen.getByDisplayValue('Beach Trip'), '{Escape}');
|
||||
await waitFor(() => expect(screen.queryByDisplayValue('Beach Trip')).not.toBeInTheDocument());
|
||||
expect(putCalls).toBe(0);
|
||||
|
||||
await user.click(within(templateRow('Beach Trip')).getByRole('button', { name: 'Edit' }));
|
||||
await user.type(screen.getByDisplayValue('Beach Trip'), ' 2{Enter}');
|
||||
await screen.findByText('Failed to save');
|
||||
expect(putCalls).toBe(1);
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-015: adding a category appends it to the expanded template', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: unknown = null;
|
||||
server.use(
|
||||
list([tmpl1]),
|
||||
detail(1, [], []),
|
||||
http.post('/api/admin/packing-templates/1/categories', async ({ request }) => {
|
||||
body = await request.json();
|
||||
return HttpResponse.json({ category: { id: 20, template_id: 1, name: 'Electronics', sort_order: 1 } });
|
||||
}),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
await user.click(screen.getByText('Beach Trip'));
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Add category' }));
|
||||
await user.type(screen.getByPlaceholderText('Category name (e.g. Clothing)'), 'Electronics{Enter}');
|
||||
|
||||
await waitFor(() => expect(body).toEqual({ name: 'Electronics' }));
|
||||
await screen.findByText('Electronics');
|
||||
expect(screen.queryByPlaceholderText('Category name (e.g. Clothing)')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-016: a blank category name is ignored and Escape closes the field', async () => {
|
||||
const user = userEvent.setup();
|
||||
let postCalls = 0;
|
||||
server.use(
|
||||
list([tmpl1]),
|
||||
detail(1, [], []),
|
||||
http.post('/api/admin/packing-templates/1/categories', () => {
|
||||
postCalls += 1;
|
||||
return HttpResponse.json({ category: { id: 20, template_id: 1, name: 'x', sort_order: 1 } });
|
||||
}),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
await user.click(screen.getByText('Beach Trip'));
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Add category' }));
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
expect(postCalls).toBe(0);
|
||||
|
||||
await user.type(screen.getByPlaceholderText('Category name (e.g. Clothing)'), 'Draft{Escape}');
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByPlaceholderText('Category name (e.g. Clothing)')).not.toBeInTheDocument(),
|
||||
);
|
||||
|
||||
// Reopening starts from an empty field and the cancel button closes it too.
|
||||
await user.click(screen.getByRole('button', { name: 'Add category' }));
|
||||
expect(screen.getByPlaceholderText('Category name (e.g. Clothing)')).toHaveValue('');
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByPlaceholderText('Category name (e.g. Clothing)')).not.toBeInTheDocument(),
|
||||
);
|
||||
expect(postCalls).toBe(0);
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-017: a failing category create toasts the save error', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
list([tmpl1]),
|
||||
detail(1, [], []),
|
||||
http.post('/api/admin/packing-templates/1/categories', () => HttpResponse.error()),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
await user.click(screen.getByText('Beach Trip'));
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Add category' }));
|
||||
await user.type(screen.getByPlaceholderText('Category name (e.g. Clothing)'), 'Electronics{Enter}');
|
||||
|
||||
await screen.findByText('Failed to save');
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-018: renaming a category updates its header', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: unknown = null;
|
||||
server.use(
|
||||
list([tmpl1]),
|
||||
detail(1, [cat1], []),
|
||||
http.put('/api/admin/packing-templates/1/categories/10', async ({ request }) => {
|
||||
body = await request.json();
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
await user.click(screen.getByText('Beach Trip'));
|
||||
await screen.findByText('Clothing');
|
||||
|
||||
await user.click(within(categoryHeader('Clothing')).getByRole('button', { name: 'Edit' }));
|
||||
const input = screen.getByDisplayValue('Clothing');
|
||||
await user.clear(input);
|
||||
await user.type(input, 'Shoes{Enter}');
|
||||
|
||||
await waitFor(() => expect(body).toEqual({ name: 'Shoes' }));
|
||||
await screen.findByText('Shoes');
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-019: Escape and an emptied field both cancel the category rename', async () => {
|
||||
const user = userEvent.setup();
|
||||
let putCalls = 0;
|
||||
server.use(
|
||||
list([tmpl1]),
|
||||
detail(1, [cat1], []),
|
||||
http.put('/api/admin/packing-templates/1/categories/10', () => {
|
||||
putCalls += 1;
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
await user.click(screen.getByText('Beach Trip'));
|
||||
await screen.findByText('Clothing');
|
||||
|
||||
await user.click(within(categoryHeader('Clothing')).getByRole('button', { name: 'Edit' }));
|
||||
await user.type(screen.getByDisplayValue('Clothing'), '{Escape}');
|
||||
await waitFor(() => expect(screen.queryByDisplayValue('Clothing')).not.toBeInTheDocument());
|
||||
|
||||
await user.click(within(categoryHeader('Clothing')).getByRole('button', { name: 'Edit' }));
|
||||
const input = screen.getByDisplayValue('Clothing');
|
||||
await user.clear(input);
|
||||
fireEvent.blur(input);
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Clothing')).toBeInTheDocument());
|
||||
expect(putCalls).toBe(0);
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-029: a failing category rename toasts and keeps the old name', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
list([tmpl1]),
|
||||
detail(1, [cat1], []),
|
||||
http.put('/api/admin/packing-templates/1/categories/10', () => HttpResponse.error()),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
await user.click(screen.getByText('Beach Trip'));
|
||||
await screen.findByText('Clothing');
|
||||
|
||||
await user.click(within(categoryHeader('Clothing')).getByRole('button', { name: 'Edit' }));
|
||||
await user.type(screen.getByDisplayValue('Clothing'), ' XL{Enter}');
|
||||
|
||||
await screen.findByText('Failed to save');
|
||||
expect(screen.getByDisplayValue('Clothing XL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-020: deleting a category drops its items too', async () => {
|
||||
const user = userEvent.setup();
|
||||
let deleted = false;
|
||||
server.use(
|
||||
list([tmpl1]),
|
||||
detail(1, [cat1], [item1, item2]),
|
||||
http.delete('/api/admin/packing-templates/1/categories/10', () => {
|
||||
deleted = true;
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
await user.click(screen.getByText('Beach Trip'));
|
||||
await screen.findByText('Clothing');
|
||||
|
||||
await user.click(within(categoryHeader('Clothing')).getByRole('button', { name: 'Delete' }));
|
||||
|
||||
await waitFor(() => expect(deleted).toBe(true));
|
||||
await waitFor(() => expect(screen.queryByText('Clothing')).not.toBeInTheDocument());
|
||||
expect(screen.queryByText('T-shirt')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Shorts')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-021: a failing category delete toasts and keeps the category', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
list([tmpl1]),
|
||||
detail(1, [cat1], [item1]),
|
||||
http.delete('/api/admin/packing-templates/1/categories/10', () => HttpResponse.error()),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
await user.click(screen.getByText('Beach Trip'));
|
||||
await screen.findByText('Clothing');
|
||||
|
||||
await user.click(within(categoryHeader('Clothing')).getByRole('button', { name: 'Delete' }));
|
||||
|
||||
await screen.findByText('Failed to delete template');
|
||||
expect(screen.getByText('Clothing')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-022: adding an item posts to the category and clears the field', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: unknown = null;
|
||||
server.use(
|
||||
list([tmpl1]),
|
||||
detail(1, [cat1], []),
|
||||
http.post('/api/admin/packing-templates/1/categories/10/items', async ({ request }) => {
|
||||
body = await request.json();
|
||||
return HttpResponse.json({ item: { id: 102, category_id: 10, name: 'Sandals', sort_order: 2 } });
|
||||
}),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
await user.click(screen.getByText('Beach Trip'));
|
||||
await screen.findByText('Clothing');
|
||||
|
||||
await user.click(within(categoryHeader('Clothing')).getByRole('button', { name: 'Item name' }));
|
||||
await user.type(screen.getByPlaceholderText('Item name'), 'Sandals{Enter}');
|
||||
|
||||
await waitFor(() => expect(body).toEqual({ name: 'Sandals' }));
|
||||
await screen.findByText('Sandals');
|
||||
expect(screen.getByPlaceholderText('Item name')).toHaveValue('');
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-023: the add-item confirm button is disabled while the field is empty', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
list([tmpl1]),
|
||||
detail(1, [cat1], []),
|
||||
http.post('/api/admin/packing-templates/1/categories/10/items', () =>
|
||||
HttpResponse.json({ item: { id: 103, category_id: 10, name: 'Hat', sort_order: 3 } }),
|
||||
),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
await user.click(screen.getByText('Beach Trip'));
|
||||
await screen.findByText('Clothing');
|
||||
|
||||
await user.click(within(categoryHeader('Clothing')).getByRole('button', { name: 'Item name' }));
|
||||
const addRow = screen.getByPlaceholderText('Item name').closest('div') as HTMLElement;
|
||||
const confirm = within(addRow).getByRole('button', { name: 'Item name' });
|
||||
expect(confirm).toBeDisabled();
|
||||
|
||||
await user.type(screen.getByPlaceholderText('Item name'), 'Hat');
|
||||
expect(confirm).toBeEnabled();
|
||||
await user.click(confirm);
|
||||
await screen.findByText('Hat');
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-024: Escape and cancel close the add-item field without posting', async () => {
|
||||
const user = userEvent.setup();
|
||||
let postCalls = 0;
|
||||
server.use(
|
||||
list([tmpl1]),
|
||||
detail(1, [cat1], []),
|
||||
http.post('/api/admin/packing-templates/1/categories/10/items', () => {
|
||||
postCalls += 1;
|
||||
return HttpResponse.json({ item: { id: 104, category_id: 10, name: 'x', sort_order: 4 } });
|
||||
}),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
await user.click(screen.getByText('Beach Trip'));
|
||||
await screen.findByText('Clothing');
|
||||
|
||||
const plus = within(categoryHeader('Clothing')).getByRole('button', { name: 'Item name' });
|
||||
await user.click(plus);
|
||||
await user.type(screen.getByPlaceholderText('Item name'), 'Draft{Escape}');
|
||||
await waitFor(() => expect(screen.queryByPlaceholderText('Item name')).not.toBeInTheDocument());
|
||||
|
||||
await user.click(plus);
|
||||
await user.type(screen.getByPlaceholderText('Item name'), 'Draft');
|
||||
const addRow = screen.getByPlaceholderText('Item name').closest('div') as HTMLElement;
|
||||
await user.click(within(addRow).getByRole('button', { name: 'Cancel' }));
|
||||
await waitFor(() => expect(screen.queryByPlaceholderText('Item name')).not.toBeInTheDocument());
|
||||
|
||||
// The plus button toggles the field shut when pressed a second time.
|
||||
await user.click(plus);
|
||||
expect(screen.getByPlaceholderText('Item name')).toBeInTheDocument();
|
||||
await user.click(plus);
|
||||
await waitFor(() => expect(screen.queryByPlaceholderText('Item name')).not.toBeInTheDocument());
|
||||
expect(postCalls).toBe(0);
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-025: a failing item create toasts the save error', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
list([tmpl1]),
|
||||
detail(1, [cat1], []),
|
||||
http.post('/api/admin/packing-templates/1/categories/10/items', () => HttpResponse.error()),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
await user.click(screen.getByText('Beach Trip'));
|
||||
await screen.findByText('Clothing');
|
||||
|
||||
await user.click(within(categoryHeader('Clothing')).getByRole('button', { name: 'Item name' }));
|
||||
await user.type(screen.getByPlaceholderText('Item name'), 'Sandals{Enter}');
|
||||
|
||||
await screen.findByText('Failed to save');
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-026: renaming an item persists via the save button', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: unknown = null;
|
||||
server.use(
|
||||
list([tmpl1]),
|
||||
detail(1, [cat1], [item1]),
|
||||
http.put('/api/admin/packing-templates/1/items/100', async ({ request }) => {
|
||||
body = await request.json();
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
await user.click(screen.getByText('Beach Trip'));
|
||||
await screen.findByText('T-shirt');
|
||||
|
||||
await user.click(within(itemRow('T-shirt')).getByRole('button', { name: 'Edit' }));
|
||||
const input = screen.getByDisplayValue('T-shirt');
|
||||
await user.clear(input);
|
||||
await user.type(input, 'Tank Top');
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
|
||||
await waitFor(() => expect(body).toEqual({ name: 'Tank Top' }));
|
||||
await screen.findByText('Tank Top');
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-027: item rename cancels on Escape, on cancel and on an empty name', async () => {
|
||||
const user = userEvent.setup();
|
||||
let putCalls = 0;
|
||||
server.use(
|
||||
list([tmpl1]),
|
||||
detail(1, [cat1], [item1]),
|
||||
http.put('/api/admin/packing-templates/1/items/100', () => {
|
||||
putCalls += 1;
|
||||
return HttpResponse.error();
|
||||
}),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
await user.click(screen.getByText('Beach Trip'));
|
||||
await screen.findByText('T-shirt');
|
||||
|
||||
await user.click(within(itemRow('T-shirt')).getByRole('button', { name: 'Edit' }));
|
||||
await user.type(screen.getByDisplayValue('T-shirt'), '{Escape}');
|
||||
await waitFor(() => expect(screen.queryByDisplayValue('T-shirt')).not.toBeInTheDocument());
|
||||
|
||||
await user.click(within(itemRow('T-shirt')).getByRole('button', { name: 'Edit' }));
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
await waitFor(() => expect(screen.queryByDisplayValue('T-shirt')).not.toBeInTheDocument());
|
||||
|
||||
await user.click(within(itemRow('T-shirt')).getByRole('button', { name: 'Edit' }));
|
||||
const input = screen.getByDisplayValue('T-shirt');
|
||||
await user.clear(input);
|
||||
await user.type(input, '{Enter}');
|
||||
await waitFor(() => expect(screen.getByText('T-shirt')).toBeInTheDocument());
|
||||
expect(putCalls).toBe(0);
|
||||
|
||||
// A rejected rename keeps the old name and toasts.
|
||||
await user.click(within(itemRow('T-shirt')).getByRole('button', { name: 'Edit' }));
|
||||
await user.type(screen.getByDisplayValue('T-shirt'), ' XL{Enter}');
|
||||
await screen.findByText('Failed to save');
|
||||
expect(putCalls).toBe(1);
|
||||
});
|
||||
|
||||
it('FE-MOB-APKG-028: deleting an item removes only that item, failures toast', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
list([tmpl1]),
|
||||
detail(1, [cat1], [item1, item2]),
|
||||
http.delete('/api/admin/packing-templates/1/items/100', () => HttpResponse.json({ success: true })),
|
||||
http.delete('/api/admin/packing-templates/1/items/101', () => HttpResponse.error()),
|
||||
);
|
||||
renderManager();
|
||||
await screen.findByText('Beach Trip');
|
||||
await user.click(screen.getByText('Beach Trip'));
|
||||
await screen.findByText('T-shirt');
|
||||
|
||||
await user.click(within(itemRow('T-shirt')).getByRole('button', { name: 'Delete' }));
|
||||
await waitFor(() => expect(screen.queryByText('T-shirt')).not.toBeInTheDocument());
|
||||
expect(screen.getByText('Shorts')).toBeInTheDocument();
|
||||
|
||||
await user.click(within(itemRow('Shorts')).getByRole('button', { name: 'Delete' }));
|
||||
await screen.findByText('Failed to delete template');
|
||||
expect(screen.getByText('Shorts')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,220 @@
|
||||
// FE-MOB-APERM-001 to FE-MOB-APERM-011
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { render, screen, waitFor } from '../../../helpers/render';
|
||||
import { server } from '../../../helpers/msw/server';
|
||||
import { resetAllStores } from '../../../helpers/store';
|
||||
import { usePermissionsStore } from '../../../../src/store/permissionsStore';
|
||||
import { ToastContainer } from '../../../../src/components/shared/Toast';
|
||||
import MAdminPermissionsPanel from '../../../../src/mobile/screens/admin/MAdminPermissionsPanel';
|
||||
|
||||
const ALLOWED = ['admin', 'trip_owner', 'trip_member', 'everybody'];
|
||||
|
||||
function buildPermission(key: string, level = 'trip_member', defaultLevel = 'trip_member') {
|
||||
return { key, level, defaultLevel, allowedLevels: [...ALLOWED] };
|
||||
}
|
||||
|
||||
const ALL_KEYS = [
|
||||
'trip_create', 'trip_edit', 'trip_delete', 'trip_archive', 'trip_cover_upload',
|
||||
'member_manage',
|
||||
'file_upload', 'file_edit', 'file_delete',
|
||||
'place_edit', 'day_edit', 'reservation_edit',
|
||||
'budget_edit', 'packing_edit', 'collab_edit', 'share_manage',
|
||||
];
|
||||
|
||||
const SAMPLE_PERMISSIONS = ALL_KEYS.map((k) => buildPermission(k));
|
||||
|
||||
function renderPanel() {
|
||||
return render(
|
||||
<>
|
||||
<ToastContainer />
|
||||
<MAdminPermissionsPanel />
|
||||
</>,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
server.use(
|
||||
http.get('/api/admin/permissions', () => HttpResponse.json({ permissions: SAMPLE_PERMISSIONS })),
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
describe('MAdminPermissionsPanel', () => {
|
||||
it('FE-MOB-APERM-001: renders only the spinner while loading', () => {
|
||||
server.use(
|
||||
http.get('/api/admin/permissions', async () => {
|
||||
await new Promise(() => {});
|
||||
return HttpResponse.json({ permissions: [] });
|
||||
}),
|
||||
);
|
||||
renderPanel();
|
||||
|
||||
expect(document.querySelector('.animate-spin')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Permission Settings')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-APERM-002: renders every category and its actions after load', async () => {
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('Permission Settings');
|
||||
expect(screen.getByText('Control who can perform actions across the application')).toBeInTheDocument();
|
||||
expect(screen.getByText('Trip Management')).toBeInTheDocument();
|
||||
expect(screen.getByText('Member Management')).toBeInTheDocument();
|
||||
expect(screen.getByText('Files')).toBeInTheDocument();
|
||||
expect(screen.getByText('Content & Schedule')).toBeInTheDocument();
|
||||
expect(screen.getByText('Budget, Packing & Collaboration')).toBeInTheDocument();
|
||||
expect(screen.getByText('Create trips')).toBeInTheDocument();
|
||||
expect(screen.getByText('Who can create new trips')).toBeInTheDocument();
|
||||
expect(screen.getAllByRole('combobox')).toHaveLength(ALL_KEYS.length);
|
||||
});
|
||||
|
||||
it('FE-MOB-APERM-003: a select reflects the stored level and offers every allowed level', async () => {
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('Permission Settings');
|
||||
const select = screen.getByRole('combobox', { name: 'Create trips' }) as HTMLSelectElement;
|
||||
expect(select.value).toBe('trip_member');
|
||||
expect(Array.from(select.options).map((o) => o.textContent)).toEqual([
|
||||
'Admin only', 'Trip owner', 'Trip members', 'Everyone',
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-MOB-APERM-004: keys missing from the payload are skipped', async () => {
|
||||
server.use(
|
||||
http.get('/api/admin/permissions', () =>
|
||||
HttpResponse.json({ permissions: [buildPermission('trip_create')] }),
|
||||
),
|
||||
);
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('Permission Settings');
|
||||
expect(screen.getByText('Create trips')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Delete trips')).not.toBeInTheDocument();
|
||||
expect(screen.getAllByRole('combobox')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-MOB-APERM-005: the customized badge shows only where level differs from the default', async () => {
|
||||
server.use(
|
||||
http.get('/api/admin/permissions', () =>
|
||||
HttpResponse.json({
|
||||
permissions: [
|
||||
buildPermission('trip_create', 'admin', 'trip_member'),
|
||||
buildPermission('trip_edit', 'trip_member', 'trip_member'),
|
||||
],
|
||||
}),
|
||||
),
|
||||
);
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('Permission Settings');
|
||||
expect(screen.getAllByText('customized')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-MOB-APERM-006: Save stays disabled until a select changes', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('Permission Settings');
|
||||
const save = screen.getByRole('button', { name: /Save/ });
|
||||
expect(save).toBeDisabled();
|
||||
|
||||
await user.selectOptions(screen.getByRole('combobox', { name: 'Create trips' }), 'admin');
|
||||
|
||||
expect(save).not.toBeDisabled();
|
||||
expect(screen.getAllByText('customized')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-MOB-APERM-007: Reset puts every value back to its default and marks the form dirty', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.get('/api/admin/permissions', () =>
|
||||
HttpResponse.json({
|
||||
permissions: [
|
||||
buildPermission('trip_create', 'admin', 'trip_member'),
|
||||
buildPermission('trip_edit', 'everybody', 'trip_owner'),
|
||||
],
|
||||
}),
|
||||
),
|
||||
);
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('Permission Settings');
|
||||
expect(screen.getAllByText('customized')).toHaveLength(2);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Reset to defaults' }));
|
||||
|
||||
await waitFor(() => expect(screen.queryByText('customized')).not.toBeInTheDocument());
|
||||
expect((screen.getByRole('combobox', { name: 'Create trips' }) as HTMLSelectElement).value).toBe('trip_member');
|
||||
expect((screen.getByRole('combobox', { name: 'Edit trip details' }) as HTMLSelectElement).value).toBe('trip_owner');
|
||||
expect(screen.getByRole('button', { name: /Save/ })).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-MOB-APERM-008: saving PUTs the current values and pushes them into the store', async () => {
|
||||
const user = userEvent.setup();
|
||||
let sent: Record<string, unknown> = {};
|
||||
server.use(
|
||||
http.put('/api/admin/permissions', async ({ request }) => {
|
||||
sent = (await request.json()) as Record<string, unknown>;
|
||||
return HttpResponse.json({ permissions: { trip_create: 'admin' } });
|
||||
}),
|
||||
);
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('Permission Settings');
|
||||
await user.selectOptions(screen.getByRole('combobox', { name: 'Create trips' }), 'admin');
|
||||
await user.click(screen.getByRole('button', { name: /Save/ }));
|
||||
|
||||
await screen.findByText('Permission settings saved');
|
||||
expect((sent.permissions as Record<string, string>).trip_create).toBe('admin');
|
||||
expect(usePermissionsStore.getState().permissions.trip_create).toBe('admin');
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: /Save/ })).toBeDisabled());
|
||||
});
|
||||
|
||||
it('FE-MOB-APERM-009: a response without permissions leaves the store untouched', async () => {
|
||||
const user = userEvent.setup();
|
||||
const before = usePermissionsStore.getState().permissions;
|
||||
server.use(http.put('/api/admin/permissions', () => HttpResponse.json({ ok: true })));
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('Permission Settings');
|
||||
await user.selectOptions(screen.getByRole('combobox', { name: 'Create trips' }), 'admin');
|
||||
await user.click(screen.getByRole('button', { name: /Save/ }));
|
||||
|
||||
await screen.findByText('Permission settings saved');
|
||||
expect(usePermissionsStore.getState().permissions).toBe(before);
|
||||
});
|
||||
|
||||
it('FE-MOB-APERM-010: a failing save toasts and keeps the form dirty', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.put('/api/admin/permissions', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
|
||||
);
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('Permission Settings');
|
||||
await user.selectOptions(screen.getByRole('combobox', { name: 'Create trips' }), 'admin');
|
||||
const save = screen.getByRole('button', { name: /Save/ });
|
||||
await user.click(save);
|
||||
|
||||
await screen.findByText('Error');
|
||||
expect(save).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-MOB-APERM-011: a failing load toasts and renders no categories', async () => {
|
||||
server.use(
|
||||
http.get('/api/admin/permissions', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
|
||||
);
|
||||
renderPanel();
|
||||
|
||||
await screen.findByText('Error');
|
||||
expect(screen.getByText('Permission Settings')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('combobox')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,422 @@
|
||||
// FE-MOB-ASET-001 to FE-MOB-ASET-023
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { render, screen, waitFor } from '../../../helpers/render';
|
||||
import { server } from '../../../helpers/msw/server';
|
||||
import { resetAllStores } from '../../../helpers/store';
|
||||
import { buildAdminHook, type AdminHook } from '../../../helpers/mobileAdmin';
|
||||
import { useTranslation } from '../../../../src/i18n';
|
||||
import MAdminSettingsSection from '../../../../src/mobile/screens/admin/MAdminSettingsSection';
|
||||
|
||||
function Harness({ admin }: { admin: AdminHook }) {
|
||||
const { t } = useTranslation();
|
||||
return <MAdminSettingsSection admin={admin} t={t} />;
|
||||
}
|
||||
|
||||
type Spy = ReturnType<typeof vi.fn>;
|
||||
type Spies = Record<string, Spy> & { toast: Record<string, Spy> };
|
||||
|
||||
function renderSettings(overrides: Record<string, unknown> = {}) {
|
||||
const admin = buildAdminHook(overrides);
|
||||
render(<Harness admin={admin} />);
|
||||
return admin as unknown as Spies;
|
||||
}
|
||||
|
||||
function toggle(label: string): HTMLElement {
|
||||
return screen.getByRole('switch', { name: label });
|
||||
}
|
||||
|
||||
/** Client ID / Client Secret are the only inputs of their type without a placeholder. */
|
||||
function unlabelledInput(type: 'text' | 'password'): HTMLInputElement {
|
||||
const inputs = Array.from(document.querySelectorAll<HTMLInputElement>(`input[type="${type}"]`));
|
||||
const match = inputs.find((i) => !i.placeholder);
|
||||
if (!match) throw new Error(`no ${type} input without a placeholder`);
|
||||
return match;
|
||||
}
|
||||
|
||||
/**
|
||||
* setOidcConfig receives an updater that reads e.target.value lazily, so the
|
||||
* spy fixture can't be replayed after the event — this harness holds the config
|
||||
* in real state instead.
|
||||
*/
|
||||
function OidcHarness() {
|
||||
const { t } = useTranslation();
|
||||
const [oidcConfig, setOidcConfig] = React.useState({
|
||||
issuer: '',
|
||||
client_id: '',
|
||||
client_secret: '',
|
||||
client_secret_set: false,
|
||||
display_name: '',
|
||||
discovery_url: '',
|
||||
});
|
||||
const admin = buildAdminHook({ oidcConfig, setOidcConfig });
|
||||
return <MAdminSettingsSection admin={admin} t={t} />;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
describe('MAdminSettingsSection', () => {
|
||||
it('FE-MOB-ASET-001: renders every card of the settings tab', () => {
|
||||
renderSettings();
|
||||
|
||||
expect(screen.getByText('Authentication Methods')).toBeInTheDocument();
|
||||
expect(screen.getByText('Passkey login')).toBeInTheDocument();
|
||||
expect(screen.getByText('Require two-factor authentication (2FA)')).toBeInTheDocument();
|
||||
// Card head and field label share the copy
|
||||
expect(screen.getAllByText('Allowed File Types')).toHaveLength(2);
|
||||
expect(screen.getByText('API Keys')).toBeInTheDocument();
|
||||
expect(screen.getByText('Single Sign-On (OIDC)')).toBeInTheDocument();
|
||||
expect(screen.getByText('Danger Zone')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-002: the OIDC toggles only appear once OIDC is configured', () => {
|
||||
renderSettings({ oidcConfigured: false });
|
||||
|
||||
expect(screen.queryByRole('switch', { name: 'SSO Login' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('switch', { name: 'SSO Auto-Provisioning' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-003: an env override disables the password toggles and shows the hint', () => {
|
||||
renderSettings({ envOverrideOidcOnly: true, oidcConfigured: true });
|
||||
|
||||
expect(
|
||||
screen.getByText(
|
||||
'Password login settings are controlled by the OIDC_ONLY environment variable and cannot be changed here.',
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
expect(toggle('Password Login')).toBeDisabled();
|
||||
expect(toggle('Password Registration')).toBeDisabled();
|
||||
expect(toggle('SSO Login')).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-004: the last remaining login method cannot be switched off', () => {
|
||||
renderSettings({ passwordLogin: false, oidcLogin: false, oidcConfigured: true });
|
||||
|
||||
expect(toggle('Password Login')).toBeDisabled();
|
||||
expect(toggle('SSO Login')).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-005: each auth toggle reports its own key and the new value', async () => {
|
||||
const user = userEvent.setup();
|
||||
const admin = renderSettings({ oidcConfigured: true, oidcLogin: true, oidcRegistration: false });
|
||||
|
||||
await user.click(toggle('Password Login'));
|
||||
expect(admin.handleToggleAuthSetting).toHaveBeenCalledWith(
|
||||
'password_login', false, admin.setPasswordLogin,
|
||||
);
|
||||
|
||||
await user.click(toggle('Password Registration'));
|
||||
expect(admin.handleToggleAuthSetting).toHaveBeenCalledWith(
|
||||
'password_registration', false, admin.setPasswordRegistration,
|
||||
);
|
||||
|
||||
await user.click(toggle('SSO Login'));
|
||||
expect(admin.handleToggleAuthSetting).toHaveBeenCalledWith('oidc_login', false, admin.setOidcLogin);
|
||||
|
||||
await user.click(toggle('SSO Auto-Provisioning'));
|
||||
expect(admin.handleToggleAuthSetting).toHaveBeenCalledWith(
|
||||
'oidc_registration', true, admin.setOidcRegistration,
|
||||
);
|
||||
|
||||
await user.click(toggle('Enable passkey login'));
|
||||
expect(admin.handleToggleAuthSetting).toHaveBeenCalledWith('passkey_login', true, admin.setPasskeyLogin);
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-006: the require-MFA toggle calls its dedicated handler', async () => {
|
||||
const user = userEvent.setup();
|
||||
const admin = renderSettings({ requireMfa: false });
|
||||
|
||||
await user.click(toggle('Require two-factor authentication (2FA)'));
|
||||
|
||||
expect(admin.handleToggleRequireMfa).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-007: the passkey warning shows only when enabled but unconfigured', () => {
|
||||
const { unmount } = render(
|
||||
<Harness admin={buildAdminHook({ passkeyLogin: true, passkeyConfigured: false })} />,
|
||||
);
|
||||
expect(
|
||||
screen.getByText(
|
||||
'No WebAuthn domain resolves for this deployment yet. Set APP_URL or the Relying Party ID below — passkeys stay hidden until then.',
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
render(<Harness admin={buildAdminHook({ passkeyLogin: true, passkeyConfigured: true })} />);
|
||||
expect(screen.queryByText(/No WebAuthn domain resolves/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-008: the WebAuthn fields render their values and save through the hook', async () => {
|
||||
const user = userEvent.setup();
|
||||
const admin = renderSettings({
|
||||
webauthnRpId: 'trek.example.org',
|
||||
webauthnOrigins: 'https://trek.example.org',
|
||||
});
|
||||
|
||||
expect(screen.getByPlaceholderText('trek.example.org')).toHaveValue('trek.example.org');
|
||||
expect(screen.getByPlaceholderText('https://trek.example.org')).toHaveValue('https://trek.example.org');
|
||||
|
||||
await user.click(screen.getAllByRole('button', { name: 'Save' })[0]);
|
||||
expect(admin.handleSaveWebauthn).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-009: editing the RP ID and origins goes through their setters', async () => {
|
||||
const user = userEvent.setup();
|
||||
const admin = renderSettings();
|
||||
|
||||
await user.type(screen.getByPlaceholderText('trek.example.org'), 'a');
|
||||
expect(admin.setWebauthnRpId).toHaveBeenCalledWith('a');
|
||||
|
||||
await user.type(screen.getByPlaceholderText('https://trek.example.org'), 'b');
|
||||
expect(admin.setWebauthnOrigins).toHaveBeenCalledWith('b');
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-010: saving the allowed file types PUTs them and reports success', async () => {
|
||||
const user = userEvent.setup();
|
||||
let sent: Record<string, unknown> = {};
|
||||
server.use(
|
||||
http.put('/api/auth/app-settings', async ({ request }) => {
|
||||
sent = (await request.json()) as Record<string, unknown>;
|
||||
return HttpResponse.json(sent);
|
||||
}),
|
||||
);
|
||||
const admin = renderSettings({ allowedFileTypes: 'jpg,png' });
|
||||
|
||||
await user.click(screen.getAllByRole('button', { name: 'Save' })[1]);
|
||||
|
||||
await waitFor(() => expect(admin.toast.success).toHaveBeenCalledWith('File type settings saved'));
|
||||
expect(sent).toEqual({ allowed_file_types: 'jpg,png' });
|
||||
expect(admin.setSavingFileTypes).toHaveBeenNthCalledWith(1, true);
|
||||
expect(admin.setSavingFileTypes).toHaveBeenLastCalledWith(false);
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-011: a failing file-types save toasts the generic error', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.put('/api/auth/app-settings', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
|
||||
);
|
||||
const admin = renderSettings();
|
||||
|
||||
await user.click(screen.getAllByRole('button', { name: 'Save' })[1]);
|
||||
|
||||
await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Error'));
|
||||
expect(admin.setSavingFileTypes).toHaveBeenLastCalledWith(false);
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-012: the file-types input writes back through its setter', async () => {
|
||||
const user = userEvent.setup();
|
||||
const admin = renderSettings({ allowedFileTypes: '' });
|
||||
|
||||
await user.type(screen.getByPlaceholderText('jpg,png,pdf,doc,docx,xls,xlsx,txt,csv'), 'p');
|
||||
expect(admin.setAllowedFileTypes).toHaveBeenCalledWith('p');
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-013: the maps key validate button is disabled without a key', () => {
|
||||
renderSettings({ mapsKey: '' });
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Test' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-014: validating a maps key calls the handler for that key type', async () => {
|
||||
const user = userEvent.setup();
|
||||
const admin = renderSettings({ mapsKey: 'AIza-test' });
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Test' }));
|
||||
|
||||
expect(admin.handleValidateKey).toHaveBeenCalledWith('maps');
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-015: the validation result renders as a valid or invalid line', () => {
|
||||
const { unmount } = render(
|
||||
<Harness admin={buildAdminHook({ mapsKey: 'k', validation: { maps: true } })} />,
|
||||
);
|
||||
expect(screen.getByText('Connected')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Invalid')).not.toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
render(<Harness admin={buildAdminHook({ mapsKey: 'k', validation: { maps: false } })} />);
|
||||
expect(screen.getByText('Invalid')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-016: the API keys card saves through the hook', async () => {
|
||||
const user = userEvent.setup();
|
||||
const admin = renderSettings();
|
||||
|
||||
await user.type(screen.getAllByPlaceholderText('Enter key...')[0], 'm');
|
||||
expect(admin.setMapsKey).toHaveBeenCalledWith('m');
|
||||
|
||||
await user.type(screen.getAllByPlaceholderText('Enter key...')[1], 'u');
|
||||
expect(admin.setUnsplashKey).toHaveBeenCalledWith('u');
|
||||
|
||||
await user.click(screen.getAllByRole('button', { name: 'Save' })[2]);
|
||||
expect(admin.handleSaveApiKeys).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-017: the Google Places toggles persist optimistically', async () => {
|
||||
const user = userEvent.setup();
|
||||
const seen: string[] = [];
|
||||
server.use(
|
||||
http.put('/api/admin/places-photos', () => {
|
||||
seen.push('photos');
|
||||
return HttpResponse.json({ enabled: true });
|
||||
}),
|
||||
http.put('/api/admin/places-autocomplete', () => {
|
||||
seen.push('autocomplete');
|
||||
return HttpResponse.json({ enabled: true });
|
||||
}),
|
||||
http.put('/api/admin/places-details', () => {
|
||||
seen.push('details');
|
||||
return HttpResponse.json({ enabled: true });
|
||||
}),
|
||||
);
|
||||
const admin = renderSettings();
|
||||
|
||||
await user.click(toggle('Place Photos'));
|
||||
await user.click(toggle('Place Autocomplete'));
|
||||
await user.click(toggle('Place Details'));
|
||||
|
||||
await waitFor(() => expect(seen).toEqual(['photos', 'autocomplete', 'details']));
|
||||
expect(admin.setPlacesPhotosEnabledState).toHaveBeenCalledWith(true);
|
||||
expect(admin.setPlacesPhotosEnabled).toHaveBeenCalledWith(true);
|
||||
expect(admin.setPlacesAutocompleteEnabled).toHaveBeenCalledWith(true);
|
||||
expect(admin.setPlacesDetailsEnabled).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-018: a rejected Places update rolls the toggle back', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.put('/api/admin/places-photos', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
|
||||
http.put('/api/admin/places-autocomplete', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
|
||||
http.put('/api/admin/places-details', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
|
||||
);
|
||||
const admin = renderSettings({
|
||||
placesPhotosEnabled: true,
|
||||
placesAutocompleteEnabled: true,
|
||||
placesDetailsEnabled: true,
|
||||
});
|
||||
|
||||
await user.click(toggle('Place Photos'));
|
||||
await user.click(toggle('Place Autocomplete'));
|
||||
await user.click(toggle('Place Details'));
|
||||
|
||||
await waitFor(() => expect(admin.setPlacesPhotosEnabledState).toHaveBeenLastCalledWith(true));
|
||||
expect(admin.setPlacesPhotosEnabled).toHaveBeenLastCalledWith(true);
|
||||
expect(admin.setPlacesAutocompleteEnabledState).toHaveBeenLastCalledWith(true);
|
||||
expect(admin.setPlacesDetailsEnabledState).toHaveBeenLastCalledWith(true);
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-019: the Open-Meteo card lists the three facts', () => {
|
||||
renderSettings();
|
||||
|
||||
expect(screen.getByText('Weather Data')).toBeInTheDocument();
|
||||
expect(screen.getByText('Free, no API key required')).toBeInTheDocument();
|
||||
expect(screen.getByText('16-day forecast')).toBeInTheDocument();
|
||||
expect(screen.getByText('10,000 requests / day')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-020: the OIDC form renders its values and saves a payload without an empty secret', async () => {
|
||||
const user = userEvent.setup();
|
||||
let sent: Record<string, unknown> = {};
|
||||
server.use(
|
||||
http.put('/api/admin/oidc', async ({ request }) => {
|
||||
sent = (await request.json()) as Record<string, unknown>;
|
||||
return HttpResponse.json(sent);
|
||||
}),
|
||||
);
|
||||
const admin = renderSettings({
|
||||
oidcConfig: {
|
||||
issuer: 'https://idp.example.org',
|
||||
client_id: 'trek',
|
||||
client_secret: '',
|
||||
client_secret_set: true,
|
||||
display_name: 'Authentik',
|
||||
discovery_url: 'https://idp.example.org/.well-known/openid-configuration',
|
||||
},
|
||||
});
|
||||
|
||||
expect(screen.getByDisplayValue('Authentik')).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue('https://idp.example.org')).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue('trek')).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText('••••••••')).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getAllByRole('button', { name: 'Save' })[3]);
|
||||
|
||||
await waitFor(() => expect(admin.toast.success).toHaveBeenCalledWith('OIDC configuration saved'));
|
||||
expect(sent).toEqual({
|
||||
issuer: 'https://idp.example.org',
|
||||
client_id: 'trek',
|
||||
display_name: 'Authentik',
|
||||
discovery_url: 'https://idp.example.org/.well-known/openid-configuration',
|
||||
});
|
||||
expect(admin.setSavingOidc).toHaveBeenLastCalledWith(false);
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-021: a filled secret is sent and a server error message is surfaced', async () => {
|
||||
const user = userEvent.setup();
|
||||
let sent: Record<string, unknown> = {};
|
||||
server.use(
|
||||
http.put('/api/admin/oidc', async ({ request }) => {
|
||||
sent = (await request.json()) as Record<string, unknown>;
|
||||
return HttpResponse.json({ error: 'Issuer unreachable' }, { status: 400 });
|
||||
}),
|
||||
);
|
||||
const admin = renderSettings({
|
||||
oidcConfig: {
|
||||
issuer: 'https://idp.example.org',
|
||||
client_id: 'trek',
|
||||
client_secret: 's3cr3t',
|
||||
client_secret_set: false,
|
||||
display_name: 'Authentik',
|
||||
discovery_url: '',
|
||||
},
|
||||
});
|
||||
|
||||
await user.click(screen.getAllByRole('button', { name: 'Save' })[3]);
|
||||
|
||||
await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Issuer unreachable'));
|
||||
expect(sent.client_secret).toBe('s3cr3t');
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-022: every OIDC input patches only its own field', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<OidcHarness />);
|
||||
|
||||
await user.type(screen.getByPlaceholderText('z.B. Google, Authentik, Keycloak'), 'Authentik');
|
||||
await user.type(screen.getByPlaceholderText('https://accounts.google.com'), 'https://idp');
|
||||
await user.type(
|
||||
screen.getByPlaceholderText(
|
||||
'https://auth.example.com/application/o/trek/.well-known/openid-configuration',
|
||||
),
|
||||
'https://idp/disco',
|
||||
);
|
||||
await user.type(unlabelledInput('text'), 'trek');
|
||||
await user.type(unlabelledInput('password'), 's3cr3t');
|
||||
|
||||
expect(screen.getByPlaceholderText('z.B. Google, Authentik, Keycloak')).toHaveValue('Authentik');
|
||||
expect(screen.getByPlaceholderText('https://accounts.google.com')).toHaveValue('https://idp');
|
||||
expect(
|
||||
screen.getByPlaceholderText(
|
||||
'https://auth.example.com/application/o/trek/.well-known/openid-configuration',
|
||||
),
|
||||
).toHaveValue('https://idp/disco');
|
||||
expect(unlabelledInput('text')).toHaveValue('trek');
|
||||
expect(unlabelledInput('password')).toHaveValue('s3cr3t');
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-023: the danger zone opens the rotate-JWT confirm', async () => {
|
||||
const user = userEvent.setup();
|
||||
const admin = renderSettings();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Rotate' }));
|
||||
|
||||
expect(admin.setShowRotateJwtModal).toHaveBeenCalledWith(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,430 @@
|
||||
// FE-MOB-ASHEET-001 to FE-MOB-ASHEET-024
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { fireEvent, render, screen, waitFor } from '../../../helpers/render';
|
||||
import { server } from '../../../helpers/msw/server';
|
||||
import { resetAllStores } from '../../../helpers/store';
|
||||
import { buildAdminHook, buildAdminUser, type AdminHook } from '../../../helpers/mobileAdmin';
|
||||
import { useTranslation } from '../../../../src/i18n';
|
||||
import MAdminSheets from '../../../../src/mobile/screens/admin/MAdminSheets';
|
||||
|
||||
function Harness({ admin }: { admin: AdminHook }) {
|
||||
const { t } = useTranslation();
|
||||
return <MAdminSheets admin={admin} t={t} />;
|
||||
}
|
||||
|
||||
type Spy = ReturnType<typeof vi.fn>;
|
||||
type Spies = Record<string, Spy> & { toast: Record<string, Spy> };
|
||||
|
||||
function renderSheets(overrides: Record<string, unknown> = {}) {
|
||||
const admin = buildAdminHook(overrides);
|
||||
render(<Harness admin={admin} />);
|
||||
return admin as unknown as Spies;
|
||||
}
|
||||
|
||||
interface UserForm {
|
||||
username: string;
|
||||
email: string;
|
||||
role: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The form inputs read e.target.value inside the state updater, so a spy setter
|
||||
* can't be inspected afterwards — React has already restored the controlled
|
||||
* value by then. These sheets therefore get real state.
|
||||
*/
|
||||
function StatefulSheets({
|
||||
initialForm,
|
||||
overrides,
|
||||
}: {
|
||||
initialForm: UserForm;
|
||||
overrides: Record<string, unknown>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [form, setForm] = React.useState<UserForm>(initialForm);
|
||||
const admin = buildAdminHook({
|
||||
...overrides,
|
||||
createForm: form,
|
||||
setCreateForm: setForm,
|
||||
editForm: form,
|
||||
setEditForm: setForm,
|
||||
});
|
||||
return <MAdminSheets admin={admin} t={t} />;
|
||||
}
|
||||
|
||||
const ME = buildAdminUser({ id: 1, username: 'admin' });
|
||||
const ALICE = buildAdminUser({ id: 2, username: 'alice', email: 'alice@example.com', role: 'user' });
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
describe('MAdminSheets', () => {
|
||||
it('FE-MOB-ASHEET-001: nothing is rendered while every sheet is closed', () => {
|
||||
renderSheets();
|
||||
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-002: the create sheet shows the four fields prefilled from createForm', () => {
|
||||
renderSheets({
|
||||
showCreateUser: true,
|
||||
createForm: { username: 'newbie', email: 'new@example.com', password: 'secret12', role: 'admin' },
|
||||
});
|
||||
|
||||
expect(screen.getByRole('dialog', { name: 'Create User' })).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText('Username')).toHaveValue('newbie');
|
||||
expect(screen.getByPlaceholderText('Email')).toHaveValue('new@example.com');
|
||||
expect(screen.getByPlaceholderText('Password')).toHaveValue('secret12');
|
||||
expect(screen.getByRole('tab', { name: 'Administrator' })).toHaveAttribute('aria-selected', 'true');
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-003: each create-form input writes through to its own field', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<StatefulSheets
|
||||
initialForm={{ username: '', email: '', role: 'user', password: '' }}
|
||||
overrides={{ showCreateUser: true }}
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.type(screen.getByPlaceholderText('Username'), 'newbie');
|
||||
await user.type(screen.getByPlaceholderText('Email'), 'new@example.com');
|
||||
await user.type(screen.getByPlaceholderText('Password'), 'secret12');
|
||||
|
||||
expect(screen.getByPlaceholderText('Username')).toHaveValue('newbie');
|
||||
expect(screen.getByPlaceholderText('Email')).toHaveValue('new@example.com');
|
||||
expect(screen.getByPlaceholderText('Password')).toHaveValue('secret12');
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-003b: the password eye toggles the input type', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderSheets({ showCreateUser: true });
|
||||
|
||||
const input = screen.getByPlaceholderText('Password');
|
||||
expect(input).toHaveAttribute('type', 'password');
|
||||
await user.click(screen.getByRole('button', { name: 'Show or hide' }));
|
||||
expect(screen.getByPlaceholderText('Password')).toHaveAttribute('type', 'text');
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-004: the role segment writes the picked role', async () => {
|
||||
const user = userEvent.setup();
|
||||
const admin = renderSheets({ showCreateUser: true });
|
||||
|
||||
await user.click(screen.getByRole('tab', { name: 'Administrator' }));
|
||||
const updater = admin.setCreateForm.mock.calls[0][0] as (f: Record<string, string>) => Record<string, string>;
|
||||
expect(updater({ username: 'a', email: 'b', password: 'c', role: 'user' }).role).toBe('admin');
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-005: create sheet footer submits and cancels', async () => {
|
||||
const user = userEvent.setup();
|
||||
const admin = renderSheets({ showCreateUser: true });
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Create User' }));
|
||||
expect(admin.handleCreateUser).toHaveBeenCalled();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
expect(admin.setShowCreateUser).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-006: the edit sheet only renders its body once a user is being edited', () => {
|
||||
renderSheets({
|
||||
editingUser: ALICE,
|
||||
editForm: { username: 'alice', email: 'alice@example.com', role: 'user', password: '' },
|
||||
});
|
||||
|
||||
expect(screen.getByRole('dialog', { name: 'Edit User' })).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue('alice')).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue('alice@example.com')).toBeInTheDocument();
|
||||
expect(screen.getByText('Reset passkeys')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-007: the edit form writes username, email, password and role separately', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<StatefulSheets
|
||||
initialForm={{ username: 'alice', email: 'alice@example.com', role: 'user', password: '' }}
|
||||
overrides={{ editingUser: ALICE }}
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.type(screen.getByDisplayValue('alice'), 'x');
|
||||
await user.type(screen.getByDisplayValue('alice@example.com'), '.uk');
|
||||
await user.type(screen.getByPlaceholderText('Enter new password…'), 'newsecret');
|
||||
await user.click(screen.getByRole('tab', { name: 'Administrator' }));
|
||||
|
||||
expect(screen.getByDisplayValue('alicex')).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue('alice@example.com.uk')).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText('Enter new password…')).toHaveValue('newsecret');
|
||||
expect(screen.getByRole('tab', { name: 'Administrator' })).toHaveAttribute('aria-selected', 'true');
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-008: saving and cancelling the edit sheet call through', async () => {
|
||||
const user = userEvent.setup();
|
||||
const admin = renderSheets({ editingUser: ALICE });
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
expect(admin.handleSaveUser).toHaveBeenCalled();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
expect(admin.setEditingUser).toHaveBeenCalledWith(null);
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-009: deleting closes the sheet first and then deletes that user', async () => {
|
||||
const user = userEvent.setup();
|
||||
const admin = renderSheets({ editingUser: ALICE, currentUser: ME });
|
||||
|
||||
const deleteBtn = screen.getByRole('button', { name: 'Delete user' });
|
||||
expect(deleteBtn).not.toBeDisabled();
|
||||
await user.click(deleteBtn);
|
||||
|
||||
expect(admin.setEditingUser).toHaveBeenCalledWith(null);
|
||||
expect(admin.handleDeleteUser).toHaveBeenCalledWith(ALICE);
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-010: the delete button is disabled for the signed-in admin', () => {
|
||||
renderSheets({ editingUser: ME, currentUser: ME });
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Delete user' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-011: resetting passkeys confirms, calls the API and reports the count', async () => {
|
||||
const user = userEvent.setup();
|
||||
let hitId = '';
|
||||
server.use(
|
||||
http.delete('/api/admin/users/:id/passkeys', ({ params }) => {
|
||||
hitId = String(params.id);
|
||||
return HttpResponse.json({ deleted: 3 });
|
||||
}),
|
||||
);
|
||||
const admin = renderSheets({ editingUser: ALICE });
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Reset passkeys' }));
|
||||
const confirm = screen.getByRole('dialog', { name: 'Reset passkeys' });
|
||||
expect(confirm).toBeInTheDocument();
|
||||
expect(screen.getByText('Remove all passkeys for alice?')).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getAllByRole('button', { name: 'Reset passkeys' })[1]);
|
||||
|
||||
await waitFor(() => expect(admin.toast.success).toHaveBeenCalledWith('Removed 3 passkey(s)'));
|
||||
expect(hitId).toBe('2');
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-012: a failing passkey reset toasts the error and keeps the sheet open', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.delete('/api/admin/users/:id/passkeys', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
|
||||
);
|
||||
const admin = renderSheets({ editingUser: ALICE });
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Reset passkeys' }));
|
||||
await user.click(screen.getAllByRole('button', { name: 'Reset passkeys' })[1]);
|
||||
|
||||
await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Error'));
|
||||
expect(screen.getByRole('dialog', { name: 'Reset passkeys' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-013: the passkey confirm can be dismissed without calling the API', async () => {
|
||||
const user = userEvent.setup();
|
||||
let called = false;
|
||||
server.use(
|
||||
http.delete('/api/admin/users/:id/passkeys', () => {
|
||||
called = true;
|
||||
return HttpResponse.json({ deleted: 0 });
|
||||
}),
|
||||
);
|
||||
renderSheets({ editingUser: ALICE });
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Reset passkeys' }));
|
||||
await user.click(screen.getAllByRole('button', { name: 'Cancel' })[1]);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByRole('dialog', { name: 'Reset passkeys' })).not.toBeInTheDocument(),
|
||||
);
|
||||
expect(called).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-014: the update sheet shows the docker commands for a docker install', () => {
|
||||
renderSheets({
|
||||
showUpdateModal: true,
|
||||
updateInfo: { update_available: true, current: '3.4.0', latest: '3.5.0', is_docker: true },
|
||||
});
|
||||
|
||||
expect(screen.getByRole('dialog', { name: 'How to Update' })).toBeInTheDocument();
|
||||
expect(screen.getByText('v3.4.0 → v3.5.0')).toBeInTheDocument();
|
||||
expect(screen.getByText(/docker pull mauriceboe\/trek:latest/)).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText(
|
||||
'Your TREK instance runs in Docker. To update to v3.5.0, run the following commands on your server:',
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.queryByRole('link', { name: /update guide/ })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-015: a non-docker install links the wiki guide instead', () => {
|
||||
renderSheets({
|
||||
showUpdateModal: true,
|
||||
updateInfo: {
|
||||
update_available: true,
|
||||
current: '3.4.0',
|
||||
latest: '3.5.0',
|
||||
is_docker: false,
|
||||
release_url: 'https://github.com/liketrek/TREK/releases/v3.5.0',
|
||||
},
|
||||
});
|
||||
|
||||
expect(screen.getByRole('link', { name: 'Open the update guide' })).toHaveAttribute(
|
||||
'href',
|
||||
'https://github.com/mauriceboe/TREK/wiki/Updating',
|
||||
);
|
||||
expect(screen.queryByText(/docker pull/)).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('link', { name: 'View on GitHub' })).toHaveAttribute(
|
||||
'href',
|
||||
'https://github.com/liketrek/TREK/releases/v3.5.0',
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-016: the update sheet closes from its footer', async () => {
|
||||
const user = userEvent.setup();
|
||||
const admin = renderSheets({
|
||||
showUpdateModal: true,
|
||||
updateInfo: { update_available: true, current: '3.4.0', latest: '3.5.0', is_docker: true },
|
||||
});
|
||||
|
||||
// Header icon button and footer button both close the sheet
|
||||
const closeButtons = screen.getAllByRole('button', { name: 'Close' });
|
||||
expect(closeButtons).toHaveLength(2);
|
||||
await user.click(closeButtons[1]);
|
||||
expect(admin.setShowUpdateModal).toHaveBeenCalledWith(false);
|
||||
|
||||
await user.click(closeButtons[0]);
|
||||
expect(admin.setShowUpdateModal).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-017: rotating the JWT secret logs the admin out and redirects', async () => {
|
||||
const user = userEvent.setup();
|
||||
let rotated = false;
|
||||
server.use(
|
||||
http.post('/api/admin/rotate-jwt-secret', () => {
|
||||
rotated = true;
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
const admin = renderSheets({ showRotateJwtModal: true });
|
||||
|
||||
expect(screen.getByRole('dialog', { name: 'Rotate JWT Secret' })).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Rotate & Log out' }));
|
||||
|
||||
await waitFor(() => expect(admin.logout).toHaveBeenCalled());
|
||||
expect(rotated).toBe(true);
|
||||
expect(admin.setRotatingJwt).toHaveBeenCalledWith(true);
|
||||
expect(admin.setShowRotateJwtModal).toHaveBeenCalledWith(false);
|
||||
expect(admin.navigate).toHaveBeenCalledWith('/login', { state: { noRedirect: true } });
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-018: a failing rotation toasts and leaves the session alone', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.post('/api/admin/rotate-jwt-secret', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
|
||||
);
|
||||
const admin = renderSheets({ showRotateJwtModal: true });
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Rotate & Log out' }));
|
||||
|
||||
await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Error'));
|
||||
expect(admin.logout).not.toHaveBeenCalled();
|
||||
expect(admin.setRotatingJwt).toHaveBeenLastCalledWith(false);
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-019: Escape and the header X close the rotate sheet', async () => {
|
||||
const user = userEvent.setup();
|
||||
const admin = renderSheets({ showRotateJwtModal: true });
|
||||
|
||||
fireEvent.keyDown(document, { key: 'Escape' });
|
||||
expect(admin.setShowRotateJwtModal).toHaveBeenCalledWith(false);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Close' }));
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
expect(admin.setShowRotateJwtModal).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-020: Escape and the header X close the create sheet', async () => {
|
||||
const user = userEvent.setup();
|
||||
const admin = renderSheets({ showCreateUser: true });
|
||||
|
||||
fireEvent.keyDown(document, { key: 'Escape' });
|
||||
await user.click(screen.getByRole('button', { name: 'Close' }));
|
||||
|
||||
expect(admin.setShowCreateUser).toHaveBeenCalledTimes(2);
|
||||
expect(admin.setShowCreateUser).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-021: Escape and the header X close the edit sheet', async () => {
|
||||
const user = userEvent.setup();
|
||||
const admin = renderSheets({ editingUser: ALICE });
|
||||
|
||||
fireEvent.keyDown(document, { key: 'Escape' });
|
||||
await user.click(screen.getByRole('button', { name: 'Close' }));
|
||||
|
||||
expect(admin.setEditingUser).toHaveBeenCalledTimes(2);
|
||||
expect(admin.setEditingUser).toHaveBeenCalledWith(null);
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-022: Escape closes the update sheet', () => {
|
||||
const admin = renderSheets({
|
||||
showUpdateModal: true,
|
||||
updateInfo: { update_available: true, current: '3.4.0', latest: '3.5.0', is_docker: true },
|
||||
});
|
||||
|
||||
fireEvent.keyDown(document, { key: 'Escape' });
|
||||
|
||||
expect(admin.setShowUpdateModal).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-023: the passkey sheet closes from Escape and from its header X', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderSheets({ editingUser: ALICE });
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Reset passkeys' }));
|
||||
fireEvent.keyDown(document, { key: 'Escape' });
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByRole('dialog', { name: 'Reset passkeys' })).not.toBeInTheDocument(),
|
||||
);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Reset passkeys' }));
|
||||
// Second dialog in the DOM is the confirm on top of the edit sheet
|
||||
await user.click(screen.getAllByRole('button', { name: 'Close' })[1]);
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByRole('dialog', { name: 'Reset passkeys' })).not.toBeInTheDocument(),
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-MOB-ASHEET-024: confirming the passkey reset without an edited user does nothing', async () => {
|
||||
const user = userEvent.setup();
|
||||
let called = false;
|
||||
server.use(
|
||||
http.delete('/api/admin/users/:id/passkeys', () => {
|
||||
called = true;
|
||||
return HttpResponse.json({ deleted: 0 });
|
||||
}),
|
||||
);
|
||||
const admin = buildAdminHook({ editingUser: ALICE });
|
||||
const { rerender } = render(<Harness admin={admin} />);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Reset passkeys' }));
|
||||
// The edit sheet closes underneath while the confirm stays open
|
||||
rerender(<Harness admin={buildAdminHook({ editingUser: null })} />);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Reset passkeys' }));
|
||||
|
||||
expect(called).toBe(false);
|
||||
expect(screen.getByRole('dialog', { name: 'Reset passkeys' })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,250 @@
|
||||
// FE-MOB-AUSERS-001 to FE-MOB-AUSERS-016
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { fireEvent, render, screen } from '../../../helpers/render';
|
||||
import { resetAllStores } from '../../../helpers/store';
|
||||
import { buildAdminHook, buildAdminUser, type AdminHook } from '../../../helpers/mobileAdmin';
|
||||
import { useTranslation } from '../../../../src/i18n';
|
||||
import MAdminUsersSection from '../../../../src/mobile/screens/admin/MAdminUsersSection';
|
||||
|
||||
// The permissions matrix self-loads and has its own suite — stub it out here.
|
||||
vi.mock('../../../../src/mobile/screens/admin/MAdminPermissionsPanel', () => ({
|
||||
default: () => <div data-testid="permissions-panel" />,
|
||||
}));
|
||||
|
||||
function Harness({ admin }: { admin: AdminHook }) {
|
||||
const { t, locale } = useTranslation();
|
||||
return <MAdminUsersSection admin={admin} t={t} locale={locale} />;
|
||||
}
|
||||
|
||||
function renderSection(overrides: Record<string, unknown> = {}) {
|
||||
const admin = buildAdminHook(overrides);
|
||||
render(<Harness admin={admin} />);
|
||||
return admin as unknown as Record<string, ReturnType<typeof vi.fn>>;
|
||||
}
|
||||
|
||||
interface InviteForm {
|
||||
max_uses: number;
|
||||
expires_in_days: number | '';
|
||||
trip_id: number | '';
|
||||
}
|
||||
|
||||
/**
|
||||
* The invite form controls read e.target.value inside the state updater, so the
|
||||
* spy fixture can't be inspected after the fact — the sheet needs real state to
|
||||
* show what a chip or the trip select actually writes.
|
||||
*/
|
||||
function InviteFormHarness({ overrides }: { overrides: Record<string, unknown> }) {
|
||||
const { t, locale } = useTranslation();
|
||||
const [inviteForm, setInviteForm] = React.useState<InviteForm>({
|
||||
max_uses: 1,
|
||||
expires_in_days: 7,
|
||||
trip_id: '',
|
||||
});
|
||||
const admin = buildAdminHook({ showCreateInvite: true, ...overrides, inviteForm, setInviteForm });
|
||||
return <MAdminUsersSection admin={admin} t={t} locale={locale} />;
|
||||
}
|
||||
|
||||
function isActiveChip(el: HTMLElement): boolean {
|
||||
return el.className.includes('bg-m-act');
|
||||
}
|
||||
|
||||
const ME = buildAdminUser({ id: 1, username: 'admin', email: 'admin@example.com', role: 'admin' });
|
||||
const ALICE = buildAdminUser({ id: 2, username: 'alice', email: 'alice@example.com', role: 'user' });
|
||||
|
||||
function buildInvite(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 1,
|
||||
token: 'abcdefghijklmnop',
|
||||
max_uses: 3,
|
||||
used_count: 1,
|
||||
expires_at: null,
|
||||
trip_title: null,
|
||||
created_by_name: 'admin',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
});
|
||||
|
||||
describe('MAdminUsersSection', () => {
|
||||
it('FE-MOB-AUSERS-001: lists users with role badges, the "you" marker and the count', () => {
|
||||
renderSection({ users: [ME, ALICE], currentUser: ME });
|
||||
|
||||
expect(screen.getByText('2 users')).toBeInTheDocument();
|
||||
expect(screen.getByText('admin')).toBeInTheDocument();
|
||||
expect(screen.getByText('alice@example.com')).toBeInTheDocument();
|
||||
expect(screen.getByText('Administrator')).toBeInTheDocument();
|
||||
expect(screen.getByText('User')).toBeInTheDocument();
|
||||
expect(screen.getByText('(You)')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AUSERS-002: users without an avatar get an initial, users with one get the image', () => {
|
||||
renderSection({ users: [ALICE, buildAdminUser({ id: 3, username: 'bob', avatar_url: '/uploads/bob.png' })] });
|
||||
|
||||
expect(screen.getByText('A')).toBeInTheDocument();
|
||||
expect(screen.getByRole('presentation')).toHaveAttribute('src', '/uploads/bob.png');
|
||||
});
|
||||
|
||||
it('FE-MOB-AUSERS-003: the spinner replaces the list while users are loading', () => {
|
||||
renderSection({ users: [ALICE], isLoading: true });
|
||||
|
||||
expect(document.querySelector('.animate-spin')).toBeInTheDocument();
|
||||
expect(screen.queryByText('alice')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AUSERS-004: tapping a row opens the edit sheet for that user', async () => {
|
||||
const user = userEvent.setup();
|
||||
const admin = renderSection({ users: [ME, ALICE], currentUser: ME });
|
||||
|
||||
await user.click(screen.getByText('alice'));
|
||||
|
||||
expect(admin.handleEditUser).toHaveBeenCalledWith(ALICE);
|
||||
});
|
||||
|
||||
it('FE-MOB-AUSERS-005: the New user button opens the create sheet', async () => {
|
||||
const user = userEvent.setup();
|
||||
const admin = renderSection();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'New user' }));
|
||||
|
||||
expect(admin.setShowCreateUser).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('FE-MOB-AUSERS-006: the invite card shows its empty state without invites', () => {
|
||||
renderSection();
|
||||
|
||||
expect(screen.getByText('Invite Links')).toBeInTheDocument();
|
||||
expect(screen.getByText('No invite links created yet')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AUSERS-007: an active invite shows the truncated token, usage and copy action', () => {
|
||||
renderSection({ invites: [buildInvite()] });
|
||||
|
||||
expect(screen.getByText('abcdefghijkl…')).toBeInTheDocument();
|
||||
expect(screen.getByText('Active')).toBeInTheDocument();
|
||||
expect(screen.getByText(/1\/3 used/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/by admin/)).toBeInTheDocument();
|
||||
expect(screen.getByTitle('Copy link')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AUSERS-008: unlimited uses render as ∞ and an expiry/trip line is appended', () => {
|
||||
renderSection({
|
||||
invites: [
|
||||
buildInvite({ max_uses: 0, used_count: 4, expires_at: '2099-01-02T00:00:00Z', trip_title: 'Japan' }),
|
||||
],
|
||||
});
|
||||
|
||||
expect(screen.getByText(/4\/∞ used/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/expires 1\/2\/2099/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/adds to Japan/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AUSERS-009: expired and used-up invites lose the copy action', () => {
|
||||
renderSection({
|
||||
invites: [
|
||||
buildInvite({ id: 1, token: 'expired-token-xx', expires_at: '2020-01-01T00:00:00Z' }),
|
||||
buildInvite({ id: 2, token: 'usedup-token-xxx', max_uses: 2, used_count: 2 }),
|
||||
],
|
||||
});
|
||||
|
||||
expect(screen.getByText('Expired')).toBeInTheDocument();
|
||||
expect(screen.getByText('Used up')).toBeInTheDocument();
|
||||
expect(screen.queryByTitle('Copy link')).not.toBeInTheDocument();
|
||||
expect(screen.getAllByTitle('Delete')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('FE-MOB-AUSERS-010: copy and delete hit the handlers with token and id', async () => {
|
||||
const user = userEvent.setup();
|
||||
const admin = renderSection({ invites: [buildInvite({ id: 7, token: 'abcdefghijklmnop' })] });
|
||||
|
||||
await user.click(screen.getByTitle('Copy link'));
|
||||
expect(admin.copyInviteLink).toHaveBeenCalledWith('abcdefghijklmnop');
|
||||
|
||||
await user.click(screen.getByTitle('Delete'));
|
||||
expect(admin.handleDeleteInvite).toHaveBeenCalledWith(7);
|
||||
});
|
||||
|
||||
it('FE-MOB-AUSERS-011: the create-invite sheet is closed until showCreateInvite flips', async () => {
|
||||
const user = userEvent.setup();
|
||||
const admin = renderSection();
|
||||
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Create Link' }));
|
||||
expect(admin.setShowCreateInvite).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('FE-MOB-AUSERS-012: the open sheet marks the active max-uses and expiry chips', () => {
|
||||
renderSection({ showCreateInvite: true, inviteForm: { max_uses: 3, expires_in_days: '', trip_id: '' } });
|
||||
|
||||
expect(screen.getByRole('dialog', { name: 'Create Link' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: '3×' }).className).toContain('bg-m-act');
|
||||
expect(screen.getByRole('button', { name: '1×' }).className).not.toContain('bg-m-act');
|
||||
// Both chip rows end in ∞ — max uses (unlimited) and expiry (never)
|
||||
const [unlimitedUses, neverExpires] = screen.getAllByRole('button', { name: '∞' });
|
||||
expect(unlimitedUses.className).not.toContain('bg-m-act');
|
||||
expect(neverExpires.className).toContain('bg-m-act');
|
||||
});
|
||||
|
||||
it('FE-MOB-AUSERS-013: chips patch only their own field of the invite form', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<InviteFormHarness overrides={{}} />);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: '5×' }));
|
||||
expect(isActiveChip(screen.getByRole('button', { name: '5×' }))).toBe(true);
|
||||
expect(isActiveChip(screen.getByRole('button', { name: '1×' }))).toBe(false);
|
||||
// The expiry row is untouched: 7d is still the active chip
|
||||
expect(isActiveChip(screen.getByRole('button', { name: '7d' }))).toBe(true);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: '14d' }));
|
||||
expect(isActiveChip(screen.getByRole('button', { name: '14d' }))).toBe(true);
|
||||
expect(isActiveChip(screen.getByRole('button', { name: '7d' }))).toBe(false);
|
||||
expect(isActiveChip(screen.getByRole('button', { name: '5×' }))).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-MOB-AUSERS-014: the trip select is hidden without trips', () => {
|
||||
renderSection({ showCreateInvite: true });
|
||||
|
||||
expect(screen.getByRole('dialog', { name: 'Create Link' })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('combobox')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Add to trip (optional)')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-AUSERS-015: the trip select stores the numeric id and maps "No trip" back to ""', async () => {
|
||||
const user = userEvent.setup();
|
||||
const handleCreateInvite = vi.fn();
|
||||
render(
|
||||
<InviteFormHarness
|
||||
overrides={{ inviteTrips: [{ id: 4, title: 'Japan 2026' }], handleCreateInvite }}
|
||||
/>,
|
||||
);
|
||||
|
||||
const select = screen.getByRole('combobox') as HTMLSelectElement;
|
||||
expect(screen.getByRole('option', { name: 'No trip' })).toBeInTheDocument();
|
||||
expect(select.value).toBe('');
|
||||
|
||||
fireEvent.change(select, { target: { value: '4' } });
|
||||
expect((screen.getByRole('combobox') as HTMLSelectElement).value).toBe('4');
|
||||
|
||||
fireEvent.change(select, { target: { value: '' } });
|
||||
expect((screen.getByRole('combobox') as HTMLSelectElement).value).toBe('');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Create & Copy' }));
|
||||
expect(handleCreateInvite).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-MOB-AUSERS-016: cancel, close and Escape all dismiss the sheet', async () => {
|
||||
const user = userEvent.setup();
|
||||
const admin = renderSection({ showCreateInvite: true });
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
expect(admin.setShowCreateInvite).toHaveBeenCalledWith(false);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Close' }));
|
||||
fireEvent.keyDown(document, { key: 'Escape' });
|
||||
expect(admin.setShowCreateInvite).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user