mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 01:44:13 +00:00
test(components): cover map, collections, settings, journey and admin
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
// FE-COMP-ACCOUNT-001 to FE-COMP-ACCOUNT-012
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
// FE-COMP-ACCOUNT-001 to FE-COMP-ACCOUNT-069
|
||||
import { render, screen, waitFor, fireEvent } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
@@ -534,3 +534,349 @@ describe('AccountTab – Role / OIDC display', () => {
|
||||
expect(screen.getByText('SSO')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
// ── Backup codes handoff (049–055) ────────────────────────────────────────────
|
||||
|
||||
const BACKUP_KEY = 'trek_mfa_backup_codes_pending';
|
||||
|
||||
function seedMfaUser() {
|
||||
seedStore(useAuthStore, {
|
||||
user: buildUser({ username: 'testuser', email: 'test@example.com', mfa_enabled: true }),
|
||||
});
|
||||
}
|
||||
|
||||
describe('AccountTab – Backup codes', () => {
|
||||
it('FE-COMP-ACCOUNT-049: a corrupt sessionStorage payload is dropped instead of rendered', async () => {
|
||||
sessionStorage.setItem(BACKUP_KEY, 'not-json');
|
||||
seedMfaUser();
|
||||
render(<AccountTab />);
|
||||
|
||||
await waitFor(() => expect(sessionStorage.getItem(BACKUP_KEY)).toBeNull());
|
||||
expect(screen.queryByText('Backup codes')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-ACCOUNT-050: a payload that is not a list of codes is ignored but kept', () => {
|
||||
sessionStorage.setItem(BACKUP_KEY, JSON.stringify({ codes: ['AAAA-1111'] }));
|
||||
seedMfaUser();
|
||||
render(<AccountTab />);
|
||||
|
||||
expect(screen.queryByText('Backup codes')).not.toBeInTheDocument();
|
||||
expect(sessionStorage.getItem(BACKUP_KEY)).not.toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-ACCOUNT-051: a blocked clipboard toasts an error', async () => {
|
||||
const user = userEvent.setup();
|
||||
Object.defineProperty(navigator, 'clipboard', {
|
||||
value: { writeText: vi.fn().mockRejectedValue(new Error('denied')) },
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
sessionStorage.setItem(BACKUP_KEY, JSON.stringify(['AAAA-1111']));
|
||||
seedMfaUser();
|
||||
render(<><ToastContainer /><AccountTab /></>);
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Copy codes' }));
|
||||
|
||||
await screen.findByText('Error');
|
||||
});
|
||||
|
||||
it('FE-COMP-ACCOUNT-052: Download TXT builds a blob, names the file and revokes the URL', async () => {
|
||||
const user = userEvent.setup();
|
||||
const createObjectURL = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:codes');
|
||||
const revokeObjectURL = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
|
||||
let downloadName = '';
|
||||
const anchorClick = vi
|
||||
.spyOn(HTMLAnchorElement.prototype, 'click')
|
||||
.mockImplementation(function (this: HTMLAnchorElement) {
|
||||
downloadName = this.download;
|
||||
});
|
||||
sessionStorage.setItem(BACKUP_KEY, JSON.stringify(['AAAA-1111']));
|
||||
seedMfaUser();
|
||||
render(<AccountTab />);
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Download TXT' }));
|
||||
|
||||
expect(createObjectURL).toHaveBeenCalledWith(expect.any(Blob));
|
||||
expect(downloadName).toBe('trek-mfa-backup-codes.txt');
|
||||
expect(revokeObjectURL).toHaveBeenCalledWith('blob:codes');
|
||||
expect(document.querySelector('a[download]')).toBeNull();
|
||||
|
||||
createObjectURL.mockRestore();
|
||||
revokeObjectURL.mockRestore();
|
||||
anchorClick.mockRestore();
|
||||
});
|
||||
|
||||
it('FE-COMP-ACCOUNT-053: Print writes the codes into the popup and triggers print', async () => {
|
||||
const user = userEvent.setup();
|
||||
const written: string[] = [];
|
||||
const print = vi.fn();
|
||||
const popup = {
|
||||
document: { open: vi.fn(), write: (html: string) => written.push(html), close: vi.fn() },
|
||||
focus: vi.fn(),
|
||||
print,
|
||||
};
|
||||
const openSpy = vi.spyOn(window, 'open').mockReturnValue(popup as unknown as Window);
|
||||
sessionStorage.setItem(BACKUP_KEY, JSON.stringify(['AAAA-1111', 'BBBB-2222']));
|
||||
seedMfaUser();
|
||||
render(<AccountTab />);
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Print / PDF' }));
|
||||
|
||||
expect(openSpy).toHaveBeenCalledWith('', '_blank', 'width=900,height=700');
|
||||
expect(written.join('')).toContain('AAAA-1111\nBBBB-2222');
|
||||
expect(popup.document.close).toHaveBeenCalled();
|
||||
expect(print).toHaveBeenCalled();
|
||||
openSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('FE-COMP-ACCOUNT-054: a blocked popup leaves printing a no-op', async () => {
|
||||
const user = userEvent.setup();
|
||||
const openSpy = vi.spyOn(window, 'open').mockReturnValue(null);
|
||||
sessionStorage.setItem(BACKUP_KEY, JSON.stringify(['AAAA-1111']));
|
||||
seedMfaUser();
|
||||
render(<AccountTab />);
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Print / PDF' }));
|
||||
|
||||
expect(openSpy).toHaveBeenCalled();
|
||||
expect(screen.getByText('Backup codes')).toBeInTheDocument();
|
||||
openSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('FE-COMP-ACCOUNT-055: dismissing the codes also clears sessionStorage', async () => {
|
||||
const user = userEvent.setup();
|
||||
sessionStorage.setItem(BACKUP_KEY, JSON.stringify(['AAAA-1111']));
|
||||
seedMfaUser();
|
||||
render(<AccountTab />);
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'OK' }));
|
||||
|
||||
expect(sessionStorage.getItem(BACKUP_KEY)).toBeNull();
|
||||
expect(screen.queryByText('Backup codes')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
// ── Avatar upload / removal (056–060) ─────────────────────────────────────────
|
||||
|
||||
describe('AccountTab – Avatar upload', () => {
|
||||
it('FE-COMP-ACCOUNT-056: picking a file uploads it and resets the input', async () => {
|
||||
const user = userEvent.setup();
|
||||
const uploadAvatar = vi.fn().mockResolvedValue(undefined);
|
||||
seedStore(useAuthStore, { uploadAvatar });
|
||||
render(<><ToastContainer /><AccountTab /></>);
|
||||
|
||||
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
const file = new File(['avatar'], 'me.png', { type: 'image/png' });
|
||||
await user.upload(input, file);
|
||||
|
||||
expect(uploadAvatar).toHaveBeenCalledWith(file);
|
||||
await screen.findByText('Profile picture updated');
|
||||
expect(input.value).toBe('');
|
||||
});
|
||||
|
||||
it('FE-COMP-ACCOUNT-057: a failing upload toasts the avatar error', async () => {
|
||||
const user = userEvent.setup();
|
||||
seedStore(useAuthStore, { uploadAvatar: vi.fn().mockRejectedValue(new Error('too big')) });
|
||||
render(<><ToastContainer /><AccountTab /></>);
|
||||
|
||||
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
await user.upload(input, new File(['avatar'], 'me.png', { type: 'image/png' }));
|
||||
|
||||
await screen.findByText('Upload failed');
|
||||
});
|
||||
|
||||
it('FE-COMP-ACCOUNT-058: a change event without a file uploads nothing', () => {
|
||||
const uploadAvatar = vi.fn().mockResolvedValue(undefined);
|
||||
seedStore(useAuthStore, { uploadAvatar });
|
||||
render(<AccountTab />);
|
||||
|
||||
fireEvent.change(document.querySelector('input[type="file"]') as HTMLInputElement);
|
||||
|
||||
expect(uploadAvatar).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-ACCOUNT-059: the remove button deletes the avatar', async () => {
|
||||
const user = userEvent.setup();
|
||||
const deleteAvatar = vi.fn().mockResolvedValue(undefined);
|
||||
seedStore(useAuthStore, {
|
||||
user: buildUser({ username: 'testuser', email: 'test@example.com', avatar_url: 'https://example.com/a.jpg' }),
|
||||
deleteAvatar,
|
||||
});
|
||||
render(<><ToastContainer /><AccountTab /></>);
|
||||
|
||||
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
const removeBtn = fileInput.parentElement!.querySelectorAll('button')[1];
|
||||
await user.click(removeBtn);
|
||||
|
||||
expect(deleteAvatar).toHaveBeenCalled();
|
||||
await screen.findByText('Profile picture removed');
|
||||
});
|
||||
|
||||
it('FE-COMP-ACCOUNT-060: a failing removal toasts the avatar error', async () => {
|
||||
const user = userEvent.setup();
|
||||
seedStore(useAuthStore, {
|
||||
user: buildUser({ username: 'testuser', email: 'test@example.com', avatar_url: 'https://example.com/a.jpg' }),
|
||||
deleteAvatar: vi.fn().mockRejectedValue(new Error('nope')),
|
||||
});
|
||||
render(<><ToastContainer /><AccountTab /></>);
|
||||
|
||||
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
await user.click(fileInput.parentElement!.querySelectorAll('button')[1]);
|
||||
|
||||
await screen.findByText('Upload failed');
|
||||
});
|
||||
});
|
||||
|
||||
// ── MFA error paths (061–064) ─────────────────────────────────────────────────
|
||||
|
||||
describe('AccountTab – MFA error paths', () => {
|
||||
it('FE-COMP-ACCOUNT-061: a failing MFA setup surfaces the server error', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.post('/api/auth/mfa/setup', () => HttpResponse.json({ error: 'Setup unavailable' }, { status: 500 })),
|
||||
);
|
||||
render(<><ToastContainer /><AccountTab /></>);
|
||||
|
||||
await user.click(screen.getByText('Set up authenticator'));
|
||||
|
||||
await screen.findByText('Setup unavailable');
|
||||
expect(screen.getByText('Set up authenticator')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-ACCOUNT-062: cancelling the setup drops the QR code and the secret', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.post('/api/auth/mfa/setup', () => HttpResponse.json({ qr_svg: '<svg>qr</svg>', secret: 'ABCDEF123' })),
|
||||
);
|
||||
render(<AccountTab />);
|
||||
|
||||
await user.click(screen.getByText('Set up authenticator'));
|
||||
await screen.findByText('ABCDEF123');
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
|
||||
expect(screen.queryByText('ABCDEF123')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('Set up authenticator')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-ACCOUNT-063: a rejected enable keeps the QR step and toasts the error', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.post('/api/auth/mfa/setup', () => HttpResponse.json({ qr_svg: '<svg>qr</svg>', secret: 'ABCDEF123' })),
|
||||
http.post('/api/auth/mfa/enable', () => HttpResponse.json({ error: 'Invalid code' }, { status: 400 })),
|
||||
);
|
||||
render(<><ToastContainer /><AccountTab /></>);
|
||||
|
||||
await user.click(screen.getByText('Set up authenticator'));
|
||||
await screen.findByText('ABCDEF123');
|
||||
await user.type(screen.getByPlaceholderText('6-digit code'), '123456');
|
||||
await user.click(screen.getByRole('button', { name: 'Enable 2FA' }));
|
||||
|
||||
await screen.findByText('Invalid code');
|
||||
expect(screen.getByText('ABCDEF123')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-ACCOUNT-064: a rejected disable toasts the error and keeps 2FA on', async () => {
|
||||
const user = userEvent.setup();
|
||||
seedMfaUser();
|
||||
server.use(
|
||||
http.post('/api/auth/mfa/disable', () => HttpResponse.json({ error: 'Wrong code' }, { status: 400 })),
|
||||
);
|
||||
render(<><ToastContainer /><AccountTab /></>);
|
||||
|
||||
const passwordInputs = document.querySelectorAll('input[type="password"]');
|
||||
await user.type(passwordInputs[passwordInputs.length - 1], 'mypassword');
|
||||
await user.type(screen.getByPlaceholderText('6-digit code'), '123456');
|
||||
await user.click(screen.getByRole('button', { name: 'Disable 2FA' }));
|
||||
|
||||
await screen.findByText('Wrong code');
|
||||
expect(screen.getByText('2FA is enabled on your account.')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
// ── Modals, hover and field edits (065–068) ───────────────────────────────────
|
||||
|
||||
function backdropOf(title: string): HTMLElement {
|
||||
return screen.getByText(title).closest('div[class*="rgba"]') as HTMLElement;
|
||||
}
|
||||
|
||||
describe('AccountTab – Modals and field edits', () => {
|
||||
it('FE-COMP-ACCOUNT-065: the confirm modal closes on the backdrop but not on the card', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<AccountTab />);
|
||||
await user.click(screen.getByText('Delete account'));
|
||||
await screen.findByText('Delete your account?');
|
||||
|
||||
await user.click(screen.getByText('Delete your account?'));
|
||||
expect(screen.getByText('Delete your account?')).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(backdropOf('Delete your account?'));
|
||||
expect(screen.queryByText('Delete your account?')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-ACCOUNT-066: the blocked modal closes on the backdrop', async () => {
|
||||
const user = userEvent.setup();
|
||||
seedStore(useAuthStore, {
|
||||
user: buildUser({ username: 'testuser', email: 'test@example.com', role: 'admin' }),
|
||||
});
|
||||
render(<AccountTab />);
|
||||
await user.click(screen.getByText('Delete account'));
|
||||
await screen.findByText('Deletion not possible');
|
||||
|
||||
fireEvent.click(backdropOf('Deletion not possible'));
|
||||
|
||||
expect(screen.queryByText('Deletion not possible')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-ACCOUNT-067: a failing deletion toasts the error and closes the modal', async () => {
|
||||
const user = userEvent.setup();
|
||||
const logout = vi.fn();
|
||||
seedStore(useAuthStore, {
|
||||
user: buildUser({ username: 'testuser', email: 'test@example.com', role: 'user' }),
|
||||
logout,
|
||||
});
|
||||
server.use(
|
||||
http.delete('/api/auth/me', () => HttpResponse.json({ error: 'Account is locked' }, { status: 400 })),
|
||||
);
|
||||
render(<><ToastContainer /><AccountTab /></>);
|
||||
|
||||
await user.click(screen.getByText('Delete account'));
|
||||
await screen.findByText('Delete your account?');
|
||||
await user.click(screen.getByText('Delete permanently'));
|
||||
|
||||
await screen.findByText('Account is locked');
|
||||
expect(logout).not.toHaveBeenCalled();
|
||||
expect(screen.queryByText('Delete your account?')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-ACCOUNT-068: editing the email field feeds the profile save', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateProfile = vi.fn().mockResolvedValue(undefined);
|
||||
seedStore(useAuthStore, { updateProfile });
|
||||
render(<AccountTab />);
|
||||
|
||||
const emailInput = screen.getByDisplayValue('test@example.com');
|
||||
await user.clear(emailInput);
|
||||
await user.type(emailInput, 'new@example.com');
|
||||
await user.click(screen.getByRole('button', { name: /save profile/i }));
|
||||
|
||||
expect(updateProfile).toHaveBeenCalledWith({ username: 'testuser', email: 'new@example.com' });
|
||||
});
|
||||
|
||||
it('FE-COMP-ACCOUNT-069: hover styling on the password and camera buttons is reverted on leave', () => {
|
||||
render(<AccountTab />);
|
||||
|
||||
const passwordBtn = screen.getByText('Update password').closest('button') as HTMLElement;
|
||||
fireEvent.mouseEnter(passwordBtn);
|
||||
expect(passwordBtn.style.background).toBe('var(--bg-hover)');
|
||||
fireEvent.mouseLeave(passwordBtn);
|
||||
expect(passwordBtn.style.background).toBe('var(--bg-card)');
|
||||
|
||||
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
const cameraBtn = fileInput.nextElementSibling as HTMLElement;
|
||||
fireEvent.mouseEnter(cameraBtn);
|
||||
expect(cameraBtn.style.transform).toBe('scale(1.15)');
|
||||
fireEvent.mouseLeave(cameraBtn);
|
||||
expect(cameraBtn.style.transform).toBe('scale(1)');
|
||||
expect(cameraBtn.style.opacity).toBe('1');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
// FE-COMP-AIRTRAIL-001 to FE-COMP-AIRTRAIL-016
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { resetAllStores } from '../../../tests/helpers/store';
|
||||
import { ToastContainer } from '../shared/Toast';
|
||||
import AirTrailConnectionSection from './AirTrailConnectionSection';
|
||||
|
||||
interface SavedBody {
|
||||
url: string;
|
||||
apiKey?: string;
|
||||
allowInsecureTls?: boolean;
|
||||
writeEnabled?: boolean;
|
||||
}
|
||||
|
||||
function stubSettings(over: Record<string, unknown> = {}) {
|
||||
server.use(
|
||||
http.get('/api/integrations/airtrail/settings', () =>
|
||||
HttpResponse.json({ url: '', allowInsecureTls: false, writeEnabled: false, connected: false, ...over }),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function renderSection() {
|
||||
return render(
|
||||
<>
|
||||
<ToastContainer />
|
||||
<AirTrailConnectionSection />
|
||||
</>,
|
||||
);
|
||||
}
|
||||
|
||||
// The desktop ToggleSwitch has no accessible name, so reach it through the label
|
||||
// text it sits next to.
|
||||
function toggleNextTo(label: string): HTMLElement {
|
||||
const row = screen.getByText(label).parentElement as HTMLElement;
|
||||
return row.querySelector('button') as HTMLElement;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
vi.clearAllMocks();
|
||||
stubSettings();
|
||||
});
|
||||
|
||||
describe('AirTrailConnectionSection', () => {
|
||||
it('FE-COMP-AIRTRAIL-001: hydrates url, toggles and the connected badge from the stored settings', async () => {
|
||||
stubSettings({ url: 'https://air.example.com', allowInsecureTls: true, writeEnabled: true, connected: true });
|
||||
renderSection();
|
||||
|
||||
expect(await screen.findByDisplayValue('https://air.example.com')).toBeInTheDocument();
|
||||
expect(toggleNextTo('Allow self-signed certificates')).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(toggleNextTo('Write changes back to AirTrail')).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(screen.getByText('Connected')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-AIRTRAIL-002: an unconfigured instance renders empty, disconnected and with both actions blocked', async () => {
|
||||
renderSection();
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: /Test connection/ })).toBeDisabled());
|
||||
expect(screen.getByRole('button', { name: /^Save$/ })).toBeDisabled();
|
||||
expect(screen.getByText('Not connected')).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText('Bearer API key')).toHaveValue('');
|
||||
expect(toggleNextTo('Allow self-signed certificates')).toHaveAttribute('aria-pressed', 'false');
|
||||
});
|
||||
|
||||
it('FE-COMP-AIRTRAIL-003: a stored key is only masked by the placeholder, never prefilled', async () => {
|
||||
stubSettings({ url: 'https://air.example.com', connected: true });
|
||||
renderSection();
|
||||
|
||||
const keyInput = await screen.findByPlaceholderText('••••••••');
|
||||
expect(keyInput).toHaveValue('');
|
||||
});
|
||||
|
||||
it('FE-COMP-AIRTRAIL-004: a failing settings fetch still ends the loading state', async () => {
|
||||
server.use(
|
||||
http.get('/api/integrations/airtrail/settings', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
// Test stays disabled for the missing URL, but the buttons leave the `loading` lock.
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: /Test connection/ })).toBeDisabled());
|
||||
expect(screen.getByText('Not connected')).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText('https://airtrail.example.com')).toHaveValue('');
|
||||
});
|
||||
|
||||
it('FE-COMP-AIRTRAIL-005: Save unlocks once a URL and a key are typed', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderSection();
|
||||
|
||||
const saveBtn = await screen.findByRole('button', { name: /^Save$/ });
|
||||
await waitFor(() => expect(saveBtn).toBeDisabled());
|
||||
|
||||
await user.type(screen.getByPlaceholderText('https://airtrail.example.com'), 'https://air.example.com');
|
||||
expect(saveBtn).toBeDisabled();
|
||||
|
||||
await user.type(screen.getByPlaceholderText('Bearer API key'), 'secret');
|
||||
expect(saveBtn).toBeEnabled();
|
||||
});
|
||||
|
||||
it('FE-COMP-AIRTRAIL-006: a connected instance saves without retyping the key', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: SavedBody | undefined;
|
||||
stubSettings({ url: 'https://air.example.com', connected: true });
|
||||
server.use(
|
||||
http.put('/api/integrations/airtrail/settings', async ({ request }) => {
|
||||
body = (await request.json()) as SavedBody;
|
||||
return HttpResponse.json({ ok: true });
|
||||
}),
|
||||
http.get('/api/integrations/airtrail/status', () => HttpResponse.json({ connected: true })),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
await screen.findByDisplayValue('https://air.example.com');
|
||||
await user.click(screen.getByRole('button', { name: /^Save$/ }));
|
||||
|
||||
await screen.findByText('AirTrail connection saved');
|
||||
expect(body).toEqual({ url: 'https://air.example.com', allowInsecureTls: false, writeEnabled: false });
|
||||
});
|
||||
|
||||
it('FE-COMP-AIRTRAIL-007: a typed key and both toggles are sent along, then the key field is cleared', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: SavedBody | undefined;
|
||||
server.use(
|
||||
http.put('/api/integrations/airtrail/settings', async ({ request }) => {
|
||||
body = (await request.json()) as SavedBody;
|
||||
return HttpResponse.json({ ok: true });
|
||||
}),
|
||||
http.get('/api/integrations/airtrail/status', () => HttpResponse.json({ connected: true })),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
await user.type(await screen.findByPlaceholderText('https://airtrail.example.com'), ' https://air.example.com ');
|
||||
await user.type(screen.getByPlaceholderText('Bearer API key'), ' tok-123 ');
|
||||
await user.click(toggleNextTo('Allow self-signed certificates'));
|
||||
await user.click(toggleNextTo('Write changes back to AirTrail'));
|
||||
await user.click(screen.getByRole('button', { name: /^Save$/ }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(body).toEqual({
|
||||
url: 'https://air.example.com',
|
||||
allowInsecureTls: true,
|
||||
writeEnabled: true,
|
||||
apiKey: 'tok-123',
|
||||
}),
|
||||
);
|
||||
await waitFor(() => expect(screen.getByPlaceholderText('••••••••')).toHaveValue(''));
|
||||
expect(screen.getByText('Connected')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-AIRTRAIL-008: a warning from the server replaces the success toast', async () => {
|
||||
const user = userEvent.setup();
|
||||
stubSettings({ url: 'https://air.example.com', connected: true });
|
||||
server.use(
|
||||
http.put('/api/integrations/airtrail/settings', () => HttpResponse.json({ warning: 'TLS verification is off' })),
|
||||
http.get('/api/integrations/airtrail/status', () => HttpResponse.json({ connected: true })),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
await screen.findByDisplayValue('https://air.example.com');
|
||||
await user.click(screen.getByRole('button', { name: /^Save$/ }));
|
||||
|
||||
await screen.findByText('TLS verification is off');
|
||||
expect(screen.queryByText('AirTrail connection saved')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-AIRTRAIL-009: a failing status probe after a successful save marks the connection dead', async () => {
|
||||
const user = userEvent.setup();
|
||||
stubSettings({ url: 'https://air.example.com', connected: true });
|
||||
server.use(
|
||||
http.put('/api/integrations/airtrail/settings', () => HttpResponse.json({ ok: true })),
|
||||
http.get('/api/integrations/airtrail/status', () => HttpResponse.json({ error: 'down' }, { status: 500 })),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
await screen.findByDisplayValue('https://air.example.com');
|
||||
await user.click(screen.getByRole('button', { name: /^Save$/ }));
|
||||
|
||||
await screen.findByText('Not connected');
|
||||
});
|
||||
|
||||
it('FE-COMP-AIRTRAIL-010: a rejected save surfaces the server error message', async () => {
|
||||
const user = userEvent.setup();
|
||||
stubSettings({ url: 'https://air.example.com', connected: true });
|
||||
server.use(
|
||||
http.put('/api/integrations/airtrail/settings', () =>
|
||||
HttpResponse.json({ error: 'Instance unreachable' }, { status: 400 }),
|
||||
),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
await screen.findByDisplayValue('https://air.example.com');
|
||||
await user.click(screen.getByRole('button', { name: /^Save$/ }));
|
||||
|
||||
await screen.findByText('Instance unreachable');
|
||||
});
|
||||
|
||||
it('FE-COMP-AIRTRAIL-011: a save failure without a server message falls back to the generic error', async () => {
|
||||
const user = userEvent.setup();
|
||||
stubSettings({ url: 'https://air.example.com', connected: true });
|
||||
server.use(
|
||||
http.put('/api/integrations/airtrail/settings', () => HttpResponse.error()),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
await screen.findByDisplayValue('https://air.example.com');
|
||||
await user.click(screen.getByRole('button', { name: /^Save$/ }));
|
||||
|
||||
await screen.findByText('Could not save the connection');
|
||||
});
|
||||
|
||||
it('FE-COMP-AIRTRAIL-012: Save is locked while the request is in flight', async () => {
|
||||
const user = userEvent.setup();
|
||||
let release!: () => void;
|
||||
stubSettings({ url: 'https://air.example.com', connected: true });
|
||||
server.use(
|
||||
http.put('/api/integrations/airtrail/settings', async () => {
|
||||
await new Promise<void>(resolve => {
|
||||
release = resolve;
|
||||
});
|
||||
return HttpResponse.json({ ok: true });
|
||||
}),
|
||||
http.get('/api/integrations/airtrail/status', () => HttpResponse.json({ connected: true })),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
await screen.findByDisplayValue('https://air.example.com');
|
||||
const saveBtn = screen.getByRole('button', { name: /^Save$/ });
|
||||
await user.click(saveBtn);
|
||||
|
||||
await waitFor(() => expect(saveBtn).toBeDisabled());
|
||||
release();
|
||||
await waitFor(() => expect(saveBtn).toBeEnabled());
|
||||
});
|
||||
|
||||
it('FE-COMP-AIRTRAIL-013: a successful test reports the flight count and flips the badge', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: { url?: string; apiKey?: string; allowInsecureTls?: boolean } | undefined;
|
||||
stubSettings({ url: 'https://air.example.com' });
|
||||
server.use(
|
||||
http.post('/api/integrations/airtrail/test', async ({ request }) => {
|
||||
body = (await request.json()) as { url?: string; allowInsecureTls?: boolean };
|
||||
return HttpResponse.json({ connected: true, flightCount: 12 });
|
||||
}),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
await screen.findByDisplayValue('https://air.example.com');
|
||||
await user.click(screen.getByRole('button', { name: /Test connection/ }));
|
||||
|
||||
await screen.findByText('Connected — 12 flight(s) found');
|
||||
expect(screen.getByText('Connected')).toBeInTheDocument();
|
||||
expect(body).toEqual({ url: 'https://air.example.com', allowInsecureTls: false });
|
||||
});
|
||||
|
||||
it('FE-COMP-AIRTRAIL-014: a test without a flight count still reports zero', async () => {
|
||||
const user = userEvent.setup();
|
||||
stubSettings({ url: 'https://air.example.com' });
|
||||
server.use(
|
||||
http.post('/api/integrations/airtrail/test', () => HttpResponse.json({ connected: true })),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
await screen.findByDisplayValue('https://air.example.com');
|
||||
await user.click(screen.getByRole('button', { name: /Test connection/ }));
|
||||
|
||||
await screen.findByText('Connected — 0 flight(s) found');
|
||||
});
|
||||
|
||||
it('FE-COMP-AIRTRAIL-015: a refused test shows the returned error and keeps the badge off', async () => {
|
||||
const user = userEvent.setup();
|
||||
stubSettings({ url: 'https://air.example.com' });
|
||||
server.use(
|
||||
http.post('/api/integrations/airtrail/test', () => HttpResponse.json({ connected: false, error: 'Bad token' })),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
await screen.findByDisplayValue('https://air.example.com');
|
||||
await user.click(screen.getByRole('button', { name: /Test connection/ }));
|
||||
|
||||
await screen.findByText('Bad token');
|
||||
expect(screen.getByText('Not connected')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-AIRTRAIL-016: a network failure during the test falls back to the generic message and shows a spinner', async () => {
|
||||
const user = userEvent.setup();
|
||||
let release!: () => void;
|
||||
stubSettings({ url: 'https://air.example.com' });
|
||||
server.use(
|
||||
http.post('/api/integrations/airtrail/test', async () => {
|
||||
await new Promise<void>(resolve => {
|
||||
release = resolve;
|
||||
});
|
||||
return HttpResponse.json({ error: 'nope' }, { status: 500 });
|
||||
}),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
await screen.findByDisplayValue('https://air.example.com');
|
||||
const testBtn = screen.getByRole('button', { name: /Test connection/ });
|
||||
await user.click(testBtn);
|
||||
|
||||
await waitFor(() => expect(testBtn).toBeDisabled());
|
||||
expect(testBtn.querySelector('.animate-spin')).not.toBeNull();
|
||||
release();
|
||||
await screen.findByText('Connection failed');
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
// FE-COMP-APPEARANCE-001+ — color mode moved here from DisplaySettingsTab,
|
||||
// plus the new scheme / readability / dashboard-widget controls.
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
import { render, screen, waitFor, fireEvent } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
@@ -8,6 +8,7 @@ import { useAuthStore } from '../../store/authStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { buildUser, buildSettings } from '../../../tests/helpers/factories';
|
||||
import { ToastContainer } from '../shared/Toast';
|
||||
import AppearanceSettingsTab from './AppearanceSettingsTab';
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -95,3 +96,206 @@ describe('AppearanceSettingsTab', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ── Custom accent, sliders, widgets and error paths (010–021) ─────────────────
|
||||
|
||||
const PERSIST = { timeout: 1500 } as const;
|
||||
|
||||
function seedAppearance(updateSetting = vi.fn().mockResolvedValue(undefined)) {
|
||||
seedStore(useSettingsStore, { settings: buildSettings({ dark_mode: 'light', language: 'en' }), updateSetting });
|
||||
return updateSetting;
|
||||
}
|
||||
|
||||
/** The last `appearance` payload the debounced persist wrote. */
|
||||
function lastAppearance(updateSetting: ReturnType<typeof vi.fn>): Record<string, unknown> {
|
||||
const calls = updateSetting.mock.calls.filter(c => c[0] === 'appearance');
|
||||
return calls[calls.length - 1][1] as Record<string, unknown>;
|
||||
}
|
||||
|
||||
describe('AppearanceSettingsTab – custom accent and sliders', () => {
|
||||
it('FE-COMP-APPEARANCE-010: a failing persist surfaces the error toast', async () => {
|
||||
const user = userEvent.setup();
|
||||
seedAppearance(vi.fn().mockRejectedValue(new Error('Appearance rejected')));
|
||||
render(<><ToastContainer /><AppearanceSettingsTab /></>);
|
||||
|
||||
await user.click(screen.getByText('Teal'));
|
||||
|
||||
await screen.findByText('Appearance rejected', undefined, PERSIST);
|
||||
});
|
||||
|
||||
it('FE-COMP-APPEARANCE-011: a failing colour-mode change surfaces the error toast', async () => {
|
||||
const user = userEvent.setup();
|
||||
seedAppearance(vi.fn().mockRejectedValue(new Error('Mode rejected')));
|
||||
render(<><ToastContainer /><AppearanceSettingsTab /></>);
|
||||
|
||||
await user.click(screen.getByText('Dark'));
|
||||
|
||||
await screen.findByText('Mode rejected');
|
||||
});
|
||||
|
||||
it('FE-COMP-APPEARANCE-012: picking Custom reveals the accent picker', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateSetting = seedAppearance();
|
||||
render(<AppearanceSettingsTab />);
|
||||
|
||||
expect(screen.queryByText('Custom accent')).not.toBeInTheDocument();
|
||||
await user.click(screen.getByText('Custom'));
|
||||
|
||||
expect(screen.getByText('Custom accent')).toBeInTheDocument();
|
||||
await waitFor(
|
||||
() => expect(updateSetting).toHaveBeenCalledWith('appearance', expect.objectContaining({ schemeId: 'custom' })),
|
||||
PERSIST,
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-COMP-APPEARANCE-013: an accent preset sets both the light and the dark accent', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateSetting = seedAppearance();
|
||||
render(<AppearanceSettingsTab />);
|
||||
|
||||
await user.click(screen.getByText('Custom'));
|
||||
await user.click(screen.getByRole('button', { name: '#0d9488' }));
|
||||
|
||||
await waitFor(
|
||||
() => expect(lastAppearance(updateSetting).accent).toEqual({ light: '#0d9488', dark: '#0d9488' }),
|
||||
PERSIST,
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-COMP-APPEARANCE-014: the two colour inputs edit the light and dark accent separately', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateSetting = seedAppearance();
|
||||
render(<AppearanceSettingsTab />);
|
||||
|
||||
await user.click(screen.getByText('Custom'));
|
||||
const [light, dark] = Array.from(document.querySelectorAll('input[type="color"]')) as HTMLInputElement[];
|
||||
|
||||
fireEvent.change(light, { target: { value: '#112233' } });
|
||||
await waitFor(() => expect(lastAppearance(updateSetting).accent).toMatchObject({ light: '#112233' }), PERSIST);
|
||||
|
||||
fireEvent.change(dark, { target: { value: '#445566' } });
|
||||
await waitFor(() => expect(lastAppearance(updateSetting).accent).toEqual({ light: '#112233', dark: '#445566' }), PERSIST);
|
||||
});
|
||||
|
||||
it('FE-COMP-APPEARANCE-015: the contrast hint follows the picked accent', async () => {
|
||||
const user = userEvent.setup();
|
||||
seedAppearance();
|
||||
render(<AppearanceSettingsTab />);
|
||||
|
||||
await user.click(screen.getByText('Custom'));
|
||||
expect(screen.getByText(/Good contrast/)).toBeInTheDocument();
|
||||
|
||||
// Near-white on white is unreadable — the hint has to say so.
|
||||
fireEvent.change(document.querySelectorAll('input[type="color"]')[0], { target: { value: '#fafafa' } });
|
||||
expect(screen.getByText(/Low contrast/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-APPEARANCE-016: reduce motion is persisted', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateSetting = seedAppearance();
|
||||
render(<AppearanceSettingsTab />);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Reduce motion' }));
|
||||
|
||||
await waitFor(
|
||||
() => expect(updateSetting).toHaveBeenCalledWith('appearance', expect.objectContaining({ reduceMotion: true })),
|
||||
PERSIST,
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-COMP-APPEARANCE-017: the global text-size slider persists fontScale', async () => {
|
||||
const updateSetting = seedAppearance();
|
||||
render(<AppearanceSettingsTab />);
|
||||
|
||||
fireEvent.change(screen.getAllByRole('slider')[0], { target: { value: '1.2' } });
|
||||
|
||||
await waitFor(() => expect(lastAppearance(updateSetting).fontScale).toBe(1.2), PERSIST);
|
||||
expect(screen.getAllByText('120%').length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('FE-COMP-APPEARANCE-018: each size row writes its own typeScale entry', async () => {
|
||||
const updateSetting = seedAppearance();
|
||||
render(<AppearanceSettingsTab />);
|
||||
const sliders = screen.getAllByRole('slider');
|
||||
|
||||
fireEvent.change(sliders[1], { target: { value: '1.15' } });
|
||||
fireEvent.change(sliders[2], { target: { value: '1.1' } });
|
||||
fireEvent.change(sliders[3], { target: { value: '0.9' } });
|
||||
fireEvent.change(sliders[4], { target: { value: '0.85' } });
|
||||
|
||||
await waitFor(
|
||||
() => expect(lastAppearance(updateSetting).typeScale).toMatchObject({
|
||||
title: 1.15,
|
||||
subtitle: 1.1,
|
||||
body: 0.9,
|
||||
caption: 0.85,
|
||||
}),
|
||||
PERSIST,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('AppearanceSettingsTab – dashboard widgets', () => {
|
||||
it('FE-COMP-APPEARANCE-019: toggling a desktop widget persists it under dashboard.desktop', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateSetting = seedAppearance();
|
||||
render(<AppearanceSettingsTab />);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Atlas / countries' }));
|
||||
|
||||
await waitFor(
|
||||
() => expect(lastAppearance(updateSetting).dashboard).toMatchObject({ desktop: { atlas: false } }),
|
||||
PERSIST,
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-COMP-APPEARANCE-020: turning the sidebar master off disables its child widgets', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateSetting = seedAppearance();
|
||||
render(<AppearanceSettingsTab />);
|
||||
const master = screen.getByRole('button', { name: 'Right sidebar' });
|
||||
expect(master).toHaveAttribute('aria-pressed', 'true');
|
||||
|
||||
await user.click(master);
|
||||
|
||||
await waitFor(
|
||||
() => expect(lastAppearance(updateSetting).dashboard).toMatchObject({ desktop: { sidebar: false } }),
|
||||
PERSIST,
|
||||
);
|
||||
expect(screen.getByRole('button', { name: 'Right sidebar' })).toHaveAttribute('aria-pressed', 'false');
|
||||
});
|
||||
|
||||
it('FE-COMP-APPEARANCE-021: toggling a mobile widget only touches the mobile map', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateSetting = seedAppearance();
|
||||
render(<AppearanceSettingsTab />);
|
||||
|
||||
// Currency exists on both devices; the second occurrence is the mobile row.
|
||||
const currencyToggles = screen.getAllByRole('button', { name: 'Currency' });
|
||||
await user.click(currencyToggles[1]);
|
||||
|
||||
await waitFor(
|
||||
() => expect(lastAppearance(updateSetting).dashboard).toMatchObject({
|
||||
desktop: { currency: true },
|
||||
mobile: { currency: false },
|
||||
}),
|
||||
PERSIST,
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-COMP-APPEARANCE-022: Reset to defaults writes the whole default config back', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateSetting = seedAppearance();
|
||||
render(<AppearanceSettingsTab />);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Atlas / countries' }));
|
||||
await waitFor(() => expect(lastAppearance(updateSetting).dashboard).toMatchObject({ desktop: { atlas: false } }), PERSIST);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Reset to defaults/ }));
|
||||
|
||||
await waitFor(
|
||||
() => expect(lastAppearance(updateSetting).dashboard).toMatchObject({ desktop: { atlas: true } }),
|
||||
PERSIST,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// FE-COMP-DISPLAY-001 to FE-COMP-DISPLAY-027
|
||||
import { render, screen, within } from '../../../tests/helpers/render';
|
||||
// FE-COMP-DISPLAY-001 to FE-COMP-DISPLAY-048
|
||||
import { render, screen, within, fireEvent } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
@@ -178,3 +178,220 @@ describe('DisplaySettingsTab', () => {
|
||||
expect(fahrenheitBtn.style.border).toContain('var(--text-primary)');
|
||||
});
|
||||
});
|
||||
|
||||
// ── Display currency (033–034) ────────────────────────────────────────────────
|
||||
|
||||
function seedFailing(message = 'Server error') {
|
||||
const updateSetting = vi.fn().mockRejectedValue(new Error(message));
|
||||
seedStore(useSettingsStore, { settings: buildSettings({ language: 'en' }), updateSetting });
|
||||
return updateSetting;
|
||||
}
|
||||
|
||||
/** The block of buttons belonging to one labelled setting. */
|
||||
function optionBlock(label: RegExp): HTMLElement {
|
||||
return screen.getByText(label).closest('div') as HTMLElement;
|
||||
}
|
||||
|
||||
describe('DisplaySettingsTab – Display currency', () => {
|
||||
it('FE-COMP-DISPLAY-033: picking "Trip currency" clears the personal display currency', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateSetting = vi.fn().mockResolvedValue(undefined);
|
||||
seedStore(useSettingsStore, { settings: buildSettings({ default_currency: 'USD' }), updateSetting });
|
||||
render(<DisplaySettingsTab />);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /USD/ }));
|
||||
await user.click(await screen.findByText('Trip currency'));
|
||||
|
||||
expect(updateSetting).toHaveBeenCalledWith('default_currency', '');
|
||||
});
|
||||
|
||||
it('FE-COMP-DISPLAY-034: a rejected currency change surfaces the error', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateSetting = vi.fn().mockRejectedValue(new Error('Currency locked'));
|
||||
seedStore(useSettingsStore, { settings: buildSettings({ default_currency: 'USD' }), updateSetting });
|
||||
render(<><ToastContainer /><DisplaySettingsTab /></>);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /USD/ }));
|
||||
await user.click(await screen.findByText('Trip currency'));
|
||||
|
||||
await screen.findByText('Currency locked');
|
||||
});
|
||||
});
|
||||
|
||||
// ── Compact language dropdown (035–039) ───────────────────────────────────────
|
||||
|
||||
function mobileLangWrap(): HTMLElement {
|
||||
return screen.getByText('Language').closest('div')!.querySelector('.sm\\:hidden') as HTMLElement;
|
||||
}
|
||||
|
||||
describe('DisplaySettingsTab – Compact language picker', () => {
|
||||
it('FE-COMP-DISPLAY-035: the compact trigger shows the active language and opens the list', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<DisplaySettingsTab />);
|
||||
const wrap = mobileLangWrap();
|
||||
|
||||
expect(within(wrap).getAllByRole('button')).toHaveLength(1);
|
||||
expect(within(wrap).getByText('English')).toBeInTheDocument();
|
||||
|
||||
await user.click(within(wrap).getByRole('button'));
|
||||
|
||||
expect(within(wrap).getAllByRole('button').length).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-DISPLAY-036: picking a language from the list saves it and closes the list', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateSetting = vi.fn().mockResolvedValue(undefined);
|
||||
seedStore(useSettingsStore, { settings: buildSettings({ language: 'en' }), updateSetting });
|
||||
render(<DisplaySettingsTab />);
|
||||
const wrap = mobileLangWrap();
|
||||
|
||||
await user.click(within(wrap).getByRole('button'));
|
||||
await user.click(within(wrap).getByText('Deutsch').closest('button')!);
|
||||
|
||||
expect(updateSetting).toHaveBeenCalledWith('language', 'de');
|
||||
expect(within(wrap).getAllByRole('button')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-DISPLAY-037: a rejected pick from the list surfaces the error', async () => {
|
||||
const user = userEvent.setup();
|
||||
seedFailing('Language locked');
|
||||
render(<><ToastContainer /><DisplaySettingsTab /></>);
|
||||
const wrap = mobileLangWrap();
|
||||
|
||||
await user.click(within(wrap).getByRole('button'));
|
||||
await user.click(within(wrap).getByText('Deutsch').closest('button')!);
|
||||
|
||||
await screen.findByText('Language locked');
|
||||
});
|
||||
|
||||
it('FE-COMP-DISPLAY-048: a rejected pick from the desktop grid surfaces the error', async () => {
|
||||
const user = userEvent.setup();
|
||||
seedFailing('Language locked');
|
||||
render(<><ToastContainer /><DisplaySettingsTab /></>);
|
||||
|
||||
await user.click(screen.getByText('Deutsch'));
|
||||
|
||||
await screen.findByText('Language locked');
|
||||
});
|
||||
|
||||
it('FE-COMP-DISPLAY-038: a mousedown outside the picker closes it', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<DisplaySettingsTab />);
|
||||
const wrap = mobileLangWrap();
|
||||
|
||||
await user.click(within(wrap).getByRole('button'));
|
||||
expect(within(wrap).getAllByRole('button').length).toBeGreaterThan(1);
|
||||
|
||||
fireEvent.mouseDown(document.body);
|
||||
|
||||
expect(within(wrap).getAllByRole('button')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-DISPLAY-039: a mousedown inside the picker keeps it open', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<DisplaySettingsTab />);
|
||||
const wrap = mobileLangWrap();
|
||||
|
||||
await user.click(within(wrap).getByRole('button'));
|
||||
fireEvent.mouseDown(within(wrap).getByText('Deutsch'));
|
||||
|
||||
expect(within(wrap).getAllByRole('button').length).toBeGreaterThan(1);
|
||||
});
|
||||
});
|
||||
|
||||
// ── Map & privacy toggles (040–047) ───────────────────────────────────────────
|
||||
|
||||
describe('DisplaySettingsTab – Map and privacy toggles', () => {
|
||||
it('FE-COMP-DISPLAY-040: turning booking route labels off persists false', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateSetting = vi.fn().mockResolvedValue(undefined);
|
||||
seedStore(useSettingsStore, { settings: buildSettings({ map_booking_labels: true }), updateSetting });
|
||||
render(<DisplaySettingsTab />);
|
||||
|
||||
await user.click(within(optionBlock(/booking route labels/i)).getByText(/^Off$/));
|
||||
|
||||
expect(updateSetting).toHaveBeenCalledWith('map_booking_labels', false);
|
||||
});
|
||||
|
||||
it('FE-COMP-DISPLAY-041: a rejected booking-labels change surfaces the error', async () => {
|
||||
const user = userEvent.setup();
|
||||
seedFailing('Labels locked');
|
||||
render(<><ToastContainer /><DisplaySettingsTab /></>);
|
||||
|
||||
await user.click(within(optionBlock(/booking route labels/i)).getByText(/^On$/));
|
||||
|
||||
await screen.findByText('Labels locked');
|
||||
});
|
||||
|
||||
it('FE-COMP-DISPLAY-042: a rejected always-show-routes change surfaces the error', async () => {
|
||||
const user = userEvent.setup();
|
||||
seedFailing('Routes locked');
|
||||
render(<><ToastContainer /><DisplaySettingsTab /></>);
|
||||
|
||||
await user.click(within(optionBlock(/always show booking routes/i)).getByText(/^On$/));
|
||||
|
||||
await screen.findByText('Routes locked');
|
||||
});
|
||||
|
||||
it('FE-COMP-DISPLAY-043: the POI pill defaults to On and can be turned off', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateSetting = vi.fn().mockResolvedValue(undefined);
|
||||
seedStore(useSettingsStore, { settings: buildSettings(), updateSetting });
|
||||
render(<DisplaySettingsTab />);
|
||||
const block = optionBlock(/explore places on the map/i);
|
||||
|
||||
expect(within(block).getByText(/^On$/).closest('button')!.style.border).toContain('var(--text-primary)');
|
||||
await user.click(within(block).getByText(/^Off$/));
|
||||
|
||||
expect(updateSetting).toHaveBeenCalledWith('map_poi_pill_enabled', false);
|
||||
});
|
||||
|
||||
it('FE-COMP-DISPLAY-044: a rejected POI pill change surfaces the error', async () => {
|
||||
const user = userEvent.setup();
|
||||
seedFailing('POI locked');
|
||||
render(<><ToastContainer /><DisplaySettingsTab /></>);
|
||||
|
||||
await user.click(within(optionBlock(/explore places on the map/i)).getByText(/^Off$/));
|
||||
|
||||
await screen.findByText('POI locked');
|
||||
});
|
||||
|
||||
it('FE-COMP-DISPLAY-045: turning blur booking codes on persists true', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateSetting = vi.fn().mockResolvedValue(undefined);
|
||||
seedStore(useSettingsStore, { settings: buildSettings({ blur_booking_codes: false }), updateSetting });
|
||||
render(<DisplaySettingsTab />);
|
||||
|
||||
await user.click(within(optionBlock(/blur booking codes/i)).getByText(/^On$/));
|
||||
|
||||
expect(updateSetting).toHaveBeenCalledWith('blur_booking_codes', true);
|
||||
});
|
||||
|
||||
it('FE-COMP-DISPLAY-046: the accommodation optimisation defaults to On and can be turned off', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateSetting = vi.fn().mockResolvedValue(undefined);
|
||||
seedStore(useSettingsStore, { settings: buildSettings(), updateSetting });
|
||||
render(<DisplaySettingsTab />);
|
||||
const block = optionBlock(/optimize route from accommodation/i);
|
||||
|
||||
expect(within(block).getByText(/^On$/).closest('button')!.style.border).toContain('var(--text-primary)');
|
||||
await user.click(within(block).getByText(/^Off$/));
|
||||
|
||||
expect(updateSetting).toHaveBeenCalledWith('optimize_from_accommodation', false);
|
||||
});
|
||||
|
||||
it('FE-COMP-DISPLAY-047: rejected blur, optimisation, distance and time-format changes all toast', async () => {
|
||||
const user = userEvent.setup();
|
||||
seedFailing('Nope');
|
||||
render(<><ToastContainer /><DisplaySettingsTab /></>);
|
||||
|
||||
await user.click(within(optionBlock(/blur booking codes/i)).getByText(/^On$/));
|
||||
await screen.findByText('Nope');
|
||||
|
||||
await user.click(within(optionBlock(/optimize route from accommodation/i)).getByText(/^Off$/));
|
||||
await user.click(screen.getByText('mi Imperial'));
|
||||
await user.click(screen.getByRole('button', { name: /24h/ }));
|
||||
|
||||
expect(screen.getAllByText('Nope').length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-COMP-INTEGRATIONS-001 to FE-COMP-INTEGRATIONS-032
|
||||
// FE-COMP-INTEGRATIONS-001 to FE-COMP-INTEGRATIONS-047
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
@@ -652,3 +652,306 @@ describe('IntegrationsTab', () => {
|
||||
await screen.findByText(/Failed to register/i);
|
||||
});
|
||||
});
|
||||
|
||||
// ── Copy buttons, cancels and the remaining failure toasts (033–047) ──────────
|
||||
|
||||
const oneClient = [
|
||||
{
|
||||
id: 'c-1',
|
||||
client_id: 'cid-1',
|
||||
name: 'Existing Client',
|
||||
redirect_uris: ['http://localhost'],
|
||||
allowed_scopes: ['trips:read'],
|
||||
created_at: '2025-01-01T00:00:00Z',
|
||||
},
|
||||
];
|
||||
const oneSession = [
|
||||
{ id: 42, client_name: 'Session App', scopes: ['trips:read'], access_token_expires_at: '2025-12-31T00:00:00Z' },
|
||||
];
|
||||
const oneToken = [
|
||||
{ id: 1, name: 'Token One', token_prefix: 'tk_one', created_at: '2025-01-01T00:00:00.000Z', last_used_at: null },
|
||||
];
|
||||
|
||||
async function openTokensTab(user: ReturnType<typeof userEvent.setup>) {
|
||||
await screen.findByText('MCP Configuration');
|
||||
await user.click(screen.getByRole('button', { name: /API Tokens/i }));
|
||||
}
|
||||
|
||||
/** The copy button inside a config panel — labelled, unlike the icon-only ones. */
|
||||
function labelledCopyButton(): HTMLElement {
|
||||
return screen.getAllByRole('button', { name: /^Copy$/i })
|
||||
.find(b => b.textContent?.trim() === 'Copy') as HTMLElement;
|
||||
}
|
||||
|
||||
describe('IntegrationsTab – copy actions and cancels', () => {
|
||||
it('FE-COMP-INTEGRATIONS-033: the OAuth client config can be expanded and copied', async () => {
|
||||
const user = userEvent.setup();
|
||||
enableMcp();
|
||||
render(<IntegrationsTab />);
|
||||
await screen.findByText('MCP Configuration');
|
||||
const writeSpy = vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue(undefined);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Client Configuration/i }));
|
||||
await user.click(labelledCopyButton());
|
||||
|
||||
expect(writeSpy).toHaveBeenCalledWith(expect.stringContaining('mcp'));
|
||||
await screen.findByRole('button', { name: /Copied!/i });
|
||||
});
|
||||
|
||||
it('FE-COMP-INTEGRATIONS-034: the API-token client config can be expanded and copied', async () => {
|
||||
const user = userEvent.setup();
|
||||
enableMcp();
|
||||
render(<IntegrationsTab />);
|
||||
await openTokensTab(user);
|
||||
const writeSpy = vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue(undefined);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Client Configuration/i }));
|
||||
await user.click(labelledCopyButton());
|
||||
|
||||
expect(writeSpy).toHaveBeenCalledWith(expect.stringContaining('mcp'));
|
||||
await screen.findByRole('button', { name: /Copied!/i });
|
||||
});
|
||||
|
||||
it('FE-COMP-INTEGRATIONS-035: Cancel closes the create-token modal', async () => {
|
||||
const user = userEvent.setup();
|
||||
enableMcp();
|
||||
render(<IntegrationsTab />);
|
||||
await openTokensTab(user);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Create New Token/i }));
|
||||
await screen.findByText('Create API Token');
|
||||
await user.click(screen.getByRole('button', { name: /^Cancel$/i }));
|
||||
|
||||
expect(screen.queryByText('Create API Token')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-INTEGRATIONS-036: the freshly created token can be copied from the modal', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.post('/api/auth/mcp-tokens', () =>
|
||||
HttpResponse.json({
|
||||
token: { id: 7, name: 'Fresh', token_prefix: 'tk_fresh', raw_token: 'tk_fresh_raw_secret', created_at: '2025-01-01T00:00:00.000Z' },
|
||||
}),
|
||||
),
|
||||
);
|
||||
enableMcp();
|
||||
render(<IntegrationsTab />);
|
||||
await openTokensTab(user);
|
||||
await user.click(screen.getByRole('button', { name: /Create New Token/i }));
|
||||
await user.type(screen.getByPlaceholderText(/Claude Desktop/i), 'Fresh');
|
||||
await user.click(screen.getByRole('button', { name: /^Create Token$/i }));
|
||||
await screen.findByText('Token Created');
|
||||
|
||||
const writeSpy = vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue(undefined);
|
||||
const copyBtns = screen.getAllByTitle('Copy');
|
||||
await user.click(copyBtns[copyBtns.length - 1]);
|
||||
|
||||
expect(writeSpy).toHaveBeenCalledWith('tk_fresh_raw_secret');
|
||||
});
|
||||
|
||||
it('FE-COMP-INTEGRATIONS-037: Cancel closes the register-client modal', async () => {
|
||||
const user = userEvent.setup();
|
||||
enableMcp();
|
||||
render(<IntegrationsTab />);
|
||||
await screen.findByText('MCP Configuration');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /New Client/i }));
|
||||
await screen.findByText('Register OAuth Client');
|
||||
await user.click(screen.getByRole('button', { name: /^Cancel$/i }));
|
||||
|
||||
expect(screen.queryByText('Register OAuth Client')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-INTEGRATIONS-038: the machine-client checkbox drops the redirect-URI field', async () => {
|
||||
const user = userEvent.setup();
|
||||
enableMcp();
|
||||
render(<IntegrationsTab />);
|
||||
await screen.findByText('MCP Configuration');
|
||||
await user.click(screen.getByRole('button', { name: /New Client/i }));
|
||||
await screen.findByText('Register OAuth Client');
|
||||
|
||||
expect(screen.getByPlaceholderText(/https:\/\/your-app/i)).toBeInTheDocument();
|
||||
await user.click(screen.getAllByRole('checkbox')[0]);
|
||||
|
||||
expect(screen.queryByPlaceholderText(/https:\/\/your-app/i)).toBeNull();
|
||||
await user.type(screen.getByPlaceholderText(/Claude Web, My MCP App/i), 'Robot');
|
||||
expect(screen.getByRole('button', { name: /Register Client/i })).toBeEnabled();
|
||||
});
|
||||
|
||||
it('FE-COMP-INTEGRATIONS-039: the created client id and secret can both be copied', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.post('/api/oauth/clients', () =>
|
||||
HttpResponse.json({
|
||||
client: {
|
||||
id: 'new-1',
|
||||
client_id: 'cid-new',
|
||||
client_secret: 'secret-new',
|
||||
name: 'Copyable',
|
||||
redirect_uris: ['http://localhost'],
|
||||
allowed_scopes: ['trips:read'],
|
||||
created_at: '2025-01-01T00:00:00Z',
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
enableMcp();
|
||||
render(<IntegrationsTab />);
|
||||
await screen.findByText('MCP Configuration');
|
||||
await user.click(screen.getByRole('button', { name: /New Client/i }));
|
||||
await user.type(screen.getByPlaceholderText(/Claude Web, My MCP App/i), 'Copyable');
|
||||
await user.type(screen.getByPlaceholderText(/https:\/\/your-app/i), 'http://localhost');
|
||||
await user.click(screen.getByRole('button', { name: /Register Client/i }));
|
||||
await screen.findByText('cid-new');
|
||||
|
||||
const writeSpy = vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue(undefined);
|
||||
const copyBtns = screen.getAllByRole('button').filter(b => b.querySelector('svg') && !b.textContent?.trim());
|
||||
await user.click(copyBtns[copyBtns.length - 2]);
|
||||
expect(writeSpy).toHaveBeenCalledWith('cid-new');
|
||||
|
||||
await user.click(copyBtns[copyBtns.length - 1]);
|
||||
expect(writeSpy).toHaveBeenCalledWith('secret-new');
|
||||
});
|
||||
|
||||
it('FE-COMP-INTEGRATIONS-040: Cancel keeps the OAuth client and closes the delete modal', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(http.get('/api/oauth/clients', () => HttpResponse.json({ clients: oneClient })));
|
||||
enableMcp();
|
||||
render(<IntegrationsTab />);
|
||||
await screen.findByText('Existing Client');
|
||||
|
||||
await user.click(screen.getByTitle('Delete Client'));
|
||||
await screen.findByRole('heading', { name: 'Delete Client' });
|
||||
await user.click(screen.getByRole('button', { name: /^Cancel$/i }));
|
||||
|
||||
expect(screen.queryByRole('heading', { name: 'Delete Client' })).toBeNull();
|
||||
expect(screen.getByText('Existing Client')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-INTEGRATIONS-041: Cancel closes the rotate-secret modal', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(http.get('/api/oauth/clients', () => HttpResponse.json({ clients: oneClient })));
|
||||
enableMcp();
|
||||
render(<IntegrationsTab />);
|
||||
await screen.findByText('Existing Client');
|
||||
|
||||
await user.click(screen.getByTitle('Rotate Secret'));
|
||||
await screen.findByRole('heading', { name: 'Rotate Secret' });
|
||||
await user.click(screen.getByRole('button', { name: /^Cancel$/i }));
|
||||
|
||||
expect(screen.queryByRole('heading', { name: 'Rotate Secret' })).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-INTEGRATIONS-042: the rotated secret can be copied and dismissed', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.get('/api/oauth/clients', () => HttpResponse.json({ clients: oneClient })),
|
||||
http.post('/api/oauth/clients/c-1/rotate', () => HttpResponse.json({ client_secret: 'rotated-xyz' })),
|
||||
);
|
||||
enableMcp();
|
||||
render(<IntegrationsTab />);
|
||||
await screen.findByText('Existing Client');
|
||||
await user.click(screen.getByTitle('Rotate Secret'));
|
||||
const rotateBtns = await screen.findAllByRole('button', { name: /^Rotate$/i });
|
||||
await user.click(rotateBtns[rotateBtns.length - 1]);
|
||||
await screen.findByText('New Secret Generated');
|
||||
|
||||
const writeSpy = vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue(undefined);
|
||||
const copyBtn = screen.getAllByRole('button').filter(b => b.querySelector('svg') && !b.textContent?.trim());
|
||||
await user.click(copyBtn[copyBtn.length - 1]);
|
||||
expect(writeSpy).toHaveBeenCalledWith('rotated-xyz');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /^Done$/i }));
|
||||
expect(screen.queryByText('New Secret Generated')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-INTEGRATIONS-043: Cancel keeps the session and closes the revoke modal', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(http.get('/api/oauth/sessions', () => HttpResponse.json({ sessions: oneSession })));
|
||||
enableMcp();
|
||||
render(<IntegrationsTab />);
|
||||
await screen.findByText('Session App');
|
||||
|
||||
await user.click(screen.getByText('Revoke'));
|
||||
await screen.findByText('Revoke Session');
|
||||
await user.click(screen.getByRole('button', { name: /^Cancel$/i }));
|
||||
|
||||
expect(screen.queryByText('Revoke Session')).toBeNull();
|
||||
expect(screen.getByText('Session App')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('IntegrationsTab – failure toasts', () => {
|
||||
it('FE-COMP-INTEGRATIONS-044: a failing token creation toasts', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(http.post('/api/auth/mcp-tokens', () => HttpResponse.json({ error: 'nope' }, { status: 500 })));
|
||||
enableMcp();
|
||||
render(<><ToastContainer /><IntegrationsTab /></>);
|
||||
await openTokensTab(user);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Create New Token/i }));
|
||||
await user.type(screen.getByPlaceholderText(/Claude Desktop/i), 'Doomed');
|
||||
await user.click(screen.getByRole('button', { name: /^Create Token$/i }));
|
||||
|
||||
await screen.findByText('Failed to create token');
|
||||
});
|
||||
|
||||
it('FE-COMP-INTEGRATIONS-045: a failing token deletion toasts and keeps the token', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.get('/api/auth/mcp-tokens', () => HttpResponse.json({ tokens: oneToken })),
|
||||
http.delete('/api/auth/mcp-tokens/1', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),
|
||||
);
|
||||
enableMcp();
|
||||
render(<><ToastContainer /><IntegrationsTab /></>);
|
||||
await openTokensTab(user);
|
||||
await screen.findByText('Token One');
|
||||
|
||||
await user.click(screen.getByTitle('Delete Token'));
|
||||
const confirmBtns = await screen.findAllByRole('button', { name: /^Delete Token$/i });
|
||||
await user.click(confirmBtns.find(b => !b.title) ?? confirmBtns[confirmBtns.length - 1]);
|
||||
|
||||
await screen.findByText('Failed to delete token');
|
||||
expect(screen.getByText('Token One')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-INTEGRATIONS-046: failing client deletion and rotation both toast', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.get('/api/oauth/clients', () => HttpResponse.json({ clients: oneClient })),
|
||||
http.delete('/api/oauth/clients/c-1', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),
|
||||
http.post('/api/oauth/clients/c-1/rotate', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),
|
||||
);
|
||||
enableMcp();
|
||||
render(<><ToastContainer /><IntegrationsTab /></>);
|
||||
await screen.findByText('Existing Client');
|
||||
|
||||
await user.click(screen.getByTitle('Delete Client'));
|
||||
const deleteBtns = await screen.findAllByRole('button', { name: /^Delete Client$/i });
|
||||
await user.click(deleteBtns[deleteBtns.length - 1]);
|
||||
await screen.findByText('Failed to delete OAuth client');
|
||||
|
||||
await user.click(screen.getByTitle('Rotate Secret'));
|
||||
const rotateBtns = await screen.findAllByRole('button', { name: /^Rotate$/i });
|
||||
await user.click(rotateBtns[rotateBtns.length - 1]);
|
||||
await screen.findByText('Failed to rotate client secret');
|
||||
});
|
||||
|
||||
it('FE-COMP-INTEGRATIONS-047: a failing session revoke toasts and keeps the session', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.get('/api/oauth/sessions', () => HttpResponse.json({ sessions: oneSession })),
|
||||
http.delete('/api/oauth/sessions/42', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),
|
||||
);
|
||||
enableMcp();
|
||||
render(<><ToastContainer /><IntegrationsTab /></>);
|
||||
await screen.findByText('Session App');
|
||||
|
||||
await user.click(screen.getByText('Revoke'));
|
||||
const revokeBtns = await screen.findAllByRole('button', { name: /^Revoke$/i });
|
||||
await user.click(revokeBtns[revokeBtns.length - 1]);
|
||||
|
||||
await screen.findByText('Failed to revoke session');
|
||||
expect(screen.getByText('Session App')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
// FE-COMP-LLM-001 to FE-COMP-LLM-013
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { buildSettings } from '../../../tests/helpers/factories';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import type { Settings } from '../../types';
|
||||
import { ToastContainer } from '../shared/Toast';
|
||||
import LlmConnectionSection from './LlmConnectionSection';
|
||||
|
||||
function seedLlm(over: Partial<Settings> = {}, updateSettings = vi.fn().mockResolvedValue(undefined)) {
|
||||
seedStore(useSettingsStore, {
|
||||
settings: buildSettings({ language: 'en', ...over }),
|
||||
isLoaded: true,
|
||||
updateSettings,
|
||||
});
|
||||
return updateSettings;
|
||||
}
|
||||
|
||||
function renderSection() {
|
||||
return render(
|
||||
<>
|
||||
<ToastContainer />
|
||||
<LlmConnectionSection />
|
||||
</>,
|
||||
);
|
||||
}
|
||||
|
||||
function multimodalToggle(): HTMLElement {
|
||||
const row = screen.getByText('Send documents as images').parentElement as HTMLElement;
|
||||
return row.querySelector('button') as HTMLElement;
|
||||
}
|
||||
|
||||
async function pickProvider(user: ReturnType<typeof userEvent.setup>, current: RegExp, next: string) {
|
||||
await user.click(screen.getByRole('button', { name: current }));
|
||||
await user.click(await screen.findByRole('button', { name: next }));
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
vi.clearAllMocks();
|
||||
seedLlm();
|
||||
});
|
||||
|
||||
describe('LlmConnectionSection', () => {
|
||||
it('FE-COMP-LLM-001: defaults to the local provider with a base URL and without a key field', () => {
|
||||
renderSection();
|
||||
|
||||
expect(screen.getByText('AI parsing')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /Local \(Ollama\)/ })).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText('http://localhost:11434')).toBeInTheDocument();
|
||||
expect(screen.queryByPlaceholderText('API key')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-LLM-002: hydrates provider, model, base URL and the multimodal toggle', () => {
|
||||
seedLlm({
|
||||
llm_provider: 'openai',
|
||||
llm_model: 'gpt-4o-mini',
|
||||
llm_base_url: 'https://api.openai.com/v1',
|
||||
llm_multimodal: true,
|
||||
});
|
||||
renderSection();
|
||||
|
||||
expect(screen.getByRole('button', { name: /OpenAI/ })).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue('gpt-4o-mini')).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue('https://api.openai.com/v1')).toBeInTheDocument();
|
||||
expect(multimodalToggle()).toHaveAttribute('aria-pressed', 'true');
|
||||
});
|
||||
|
||||
it('FE-COMP-LLM-003: nothing is hydrated and Save stays locked while the settings are loading', () => {
|
||||
seedStore(useSettingsStore, {
|
||||
settings: buildSettings({ language: 'en', llm_provider: 'anthropic', llm_model: 'claude-sonnet' }),
|
||||
isLoaded: false,
|
||||
});
|
||||
renderSection();
|
||||
|
||||
expect(screen.getByRole('button', { name: /Local \(Ollama\)/ })).toBeInTheDocument();
|
||||
expect(screen.queryByDisplayValue('claude-sonnet')).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /^Save$/ })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-COMP-LLM-004: a stored key drives the masked placeholder and is never prefilled', () => {
|
||||
seedLlm({ llm_provider: 'anthropic', llm_api_key: '***' });
|
||||
renderSection();
|
||||
|
||||
expect(screen.getByPlaceholderText('••••••••')).toHaveValue('');
|
||||
expect(screen.queryByPlaceholderText('http://localhost:11434')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-LLM-005: without a stored key the field falls back to the plain label placeholder', () => {
|
||||
seedLlm({ llm_provider: 'anthropic' });
|
||||
renderSection();
|
||||
|
||||
expect(screen.getByPlaceholderText('API key')).toHaveValue('');
|
||||
});
|
||||
|
||||
it('FE-COMP-LLM-006: picking Anthropic hides the base URL and reveals the key field', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderSection();
|
||||
|
||||
await pickProvider(user, /Local \(Ollama\)/, 'Anthropic');
|
||||
|
||||
expect(screen.queryByPlaceholderText('http://localhost:11434')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('Stored encrypted. Leave blank to keep the current key.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-LLM-007: picking OpenAI keeps the base URL and adds the key field', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderSection();
|
||||
|
||||
await pickProvider(user, /Local \(Ollama\)/, 'OpenAI');
|
||||
|
||||
expect(screen.getByPlaceholderText('http://localhost:11434')).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText('API key')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-LLM-008: saving trims the inputs and omits the key when none was typed', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateSettings = seedLlm({ llm_model: '', llm_base_url: '' });
|
||||
renderSection();
|
||||
|
||||
await user.type(screen.getByPlaceholderText('qwen3:8b'), ' qwen3:8b ');
|
||||
await user.type(screen.getByPlaceholderText('http://localhost:11434'), ' http://ollama.local ');
|
||||
await user.click(screen.getByRole('button', { name: /^Save$/ }));
|
||||
|
||||
expect(updateSettings).toHaveBeenCalledWith({
|
||||
llm_provider: 'local',
|
||||
llm_model: 'qwen3:8b',
|
||||
llm_base_url: 'http://ollama.local',
|
||||
llm_multimodal: false,
|
||||
});
|
||||
await screen.findByText('AI settings saved');
|
||||
});
|
||||
|
||||
it('FE-COMP-LLM-009: a typed key is sent, the field is cleared and the mask takes over', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateSettings = seedLlm({ llm_provider: 'anthropic', llm_model: 'claude-sonnet' });
|
||||
renderSection();
|
||||
|
||||
await user.type(screen.getByPlaceholderText('API key'), ' sk-test ');
|
||||
await user.click(screen.getByRole('button', { name: /^Save$/ }));
|
||||
|
||||
expect(updateSettings).toHaveBeenCalledWith(expect.objectContaining({ llm_api_key: 'sk-test' }));
|
||||
await waitFor(() => expect(screen.getByPlaceholderText('••••••••')).toHaveValue(''));
|
||||
});
|
||||
|
||||
it('FE-COMP-LLM-010: a non-local provider never persists a base URL', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateSettings = seedLlm({ llm_provider: 'anthropic', llm_base_url: 'http://leftover' });
|
||||
renderSection();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /^Save$/ }));
|
||||
|
||||
expect(updateSettings).toHaveBeenCalledWith(expect.objectContaining({ llm_base_url: '' }));
|
||||
});
|
||||
|
||||
it('FE-COMP-LLM-011: the multimodal toggle is part of the saved payload', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateSettings = seedLlm();
|
||||
renderSection();
|
||||
|
||||
await user.click(multimodalToggle());
|
||||
expect(multimodalToggle()).toHaveAttribute('aria-pressed', 'true');
|
||||
await user.click(screen.getByRole('button', { name: /^Save$/ }));
|
||||
|
||||
expect(updateSettings).toHaveBeenCalledWith(expect.objectContaining({ llm_multimodal: true }));
|
||||
});
|
||||
|
||||
it('FE-COMP-LLM-012: a failing save shows the error toast and re-enables the button', async () => {
|
||||
const user = userEvent.setup();
|
||||
seedLlm({}, vi.fn().mockRejectedValue(new Error('nope')));
|
||||
renderSection();
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /^Save$/ });
|
||||
await user.click(saveBtn);
|
||||
|
||||
await screen.findByText('Could not save AI settings');
|
||||
await waitFor(() => expect(saveBtn).toBeEnabled());
|
||||
});
|
||||
|
||||
it('FE-COMP-LLM-013: Save is locked while the request is in flight', async () => {
|
||||
const user = userEvent.setup();
|
||||
let release!: () => void;
|
||||
seedLlm({}, vi.fn().mockReturnValue(new Promise<void>(resolve => {
|
||||
release = resolve;
|
||||
})));
|
||||
renderSection();
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /^Save$/ });
|
||||
await user.click(saveBtn);
|
||||
|
||||
await waitFor(() => expect(saveBtn).toBeDisabled());
|
||||
release();
|
||||
await waitFor(() => expect(saveBtn).toBeEnabled());
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
// FE-COMP-MAP-001 to FE-COMP-MAP-017
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
// FE-COMP-MAP-001 to FE-COMP-MAP-030
|
||||
import { render, screen, waitFor, within, fireEvent } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
@@ -15,6 +15,23 @@ vi.mock('../Map/MapView', () => ({
|
||||
),
|
||||
}));
|
||||
|
||||
// The GL preview boots a real mapbox/maplibre instance; the tab only cares that
|
||||
// it gets the right provider/style, so render those as data attributes.
|
||||
vi.mock('./MapboxPreview', () => ({
|
||||
default: ({ provider, style, token, enable3d, quality }: {
|
||||
provider?: string; style: string; token?: string; enable3d: boolean; quality?: boolean;
|
||||
}) => (
|
||||
<div
|
||||
data-testid="gl-preview"
|
||||
data-provider={provider}
|
||||
data-style={style}
|
||||
data-token={token}
|
||||
data-3d={String(enable3d)}
|
||||
data-quality={String(quality)}
|
||||
/>
|
||||
),
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
vi.clearAllMocks();
|
||||
@@ -138,3 +155,196 @@ describe('MapSettingsTab', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ── Provider switching and GL settings (018–030) ──────────────────────────────
|
||||
|
||||
const MAPBOX_STANDARD = 'mapbox://styles/mapbox/standard';
|
||||
const OFM_LIBERTY = 'https://tiles.openfreemap.org/styles/liberty';
|
||||
|
||||
/** The style preset picker sitting above the raw style input. */
|
||||
function styleDropdown(): HTMLElement {
|
||||
return screen.getByText('Map Style').closest('div')!.querySelector('div.relative') as HTMLElement;
|
||||
}
|
||||
|
||||
/** The ToggleSwitch belonging to a labelled GL option row. */
|
||||
function toggleFor(label: string): HTMLElement {
|
||||
let el: HTMLElement | null = screen.getByText(label);
|
||||
while (el && !el.querySelector('button')) el = el.parentElement;
|
||||
return el!.querySelector('button') as HTMLElement;
|
||||
}
|
||||
|
||||
describe('MapSettingsTab – GL providers', () => {
|
||||
it('FE-COMP-MAP-018: picking Mapbox GL reveals the token field, the style picker and the preview', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<MapSettingsTab />);
|
||||
|
||||
await user.click(screen.getByText('Mapbox GL'));
|
||||
|
||||
expect(screen.getByText('Mapbox Access Token')).toBeInTheDocument();
|
||||
expect(screen.getByText('Map Style')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Map Template')).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('gl-preview')).toHaveAttribute('data-provider', 'mapbox-gl');
|
||||
expect(screen.getByDisplayValue(MAPBOX_STANDARD)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-MAP-019: the style picker lists presets with their tag chips and applies the pick', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<MapSettingsTab />);
|
||||
await user.click(screen.getByText('Mapbox GL'));
|
||||
|
||||
const dropdown = styleDropdown();
|
||||
await user.click(within(dropdown).getByRole('button'));
|
||||
|
||||
expect(within(dropdown).getByText('Satellite Streets')).toBeInTheDocument();
|
||||
expect(within(dropdown).getAllByText('Apple-like').length).toBeGreaterThan(0);
|
||||
|
||||
await user.click(within(dropdown).getByText('Streets'));
|
||||
|
||||
expect(screen.getByDisplayValue('mapbox://styles/mapbox/streets-v12')).toBeInTheDocument();
|
||||
expect(within(dropdown).queryByText('Satellite Streets')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-MAP-020: a mousedown outside the style picker closes it', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<MapSettingsTab />);
|
||||
await user.click(screen.getByText('Mapbox GL'));
|
||||
|
||||
const dropdown = styleDropdown();
|
||||
await user.click(within(dropdown).getByRole('button'));
|
||||
expect(within(dropdown).getByText('Satellite Streets')).toBeInTheDocument();
|
||||
|
||||
fireEvent.mouseDown(document.body);
|
||||
|
||||
expect(within(dropdown).queryByText('Satellite Streets')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-MAP-021: a custom style falls back to the picker placeholder', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<MapSettingsTab />);
|
||||
await user.click(screen.getByText('Mapbox GL'));
|
||||
|
||||
const styleInput = screen.getByDisplayValue(MAPBOX_STANDARD);
|
||||
await user.clear(styleInput);
|
||||
await user.type(styleInput, 'mapbox://styles/me/custom');
|
||||
|
||||
expect(within(styleDropdown()).getByText('Select a Mapbox style')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-MAP-022: MapLibre needs no token and swaps in the OpenFreeMap presets', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<MapSettingsTab />);
|
||||
|
||||
await user.click(screen.getByText('MapLibre GL'));
|
||||
|
||||
expect(screen.queryByText('Mapbox Access Token')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('3D Buildings & Terrain')).not.toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue(OFM_LIBERTY)).toBeInTheDocument();
|
||||
expect(screen.getByText('Preset or OpenFreeMap style URL. OpenFreeMap styles work without a token.')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('gl-preview')).toHaveAttribute('data-provider', 'maplibre-gl');
|
||||
});
|
||||
|
||||
it('FE-COMP-MAP-023: switching from MapLibre back to Mapbox drops the OpenFreeMap style', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<MapSettingsTab />);
|
||||
|
||||
await user.click(screen.getByText('MapLibre GL'));
|
||||
expect(screen.getByDisplayValue(OFM_LIBERTY)).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByText('Mapbox GL'));
|
||||
|
||||
expect(screen.getByDisplayValue(MAPBOX_STANDARD)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-MAP-024: switching back to Leaflet restores the tile-template fields', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<MapSettingsTab />);
|
||||
|
||||
await user.click(screen.getByText('Mapbox GL'));
|
||||
await user.click(screen.getByText('Leaflet'));
|
||||
|
||||
expect(screen.getByText('Map Template')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('gl-preview')).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('map-view')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-MAP-025: the token typed into the field reaches the preview', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<MapSettingsTab />);
|
||||
await user.click(screen.getByText('Mapbox GL'));
|
||||
|
||||
await user.type(screen.getByPlaceholderText('pk.eyJ1Ijoi...'), 'pk.token');
|
||||
|
||||
expect(screen.getByTestId('gl-preview')).toHaveAttribute('data-token', 'pk.token');
|
||||
});
|
||||
|
||||
it('FE-COMP-MAP-026: the 3D and quality toggles drive the preview', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<MapSettingsTab />);
|
||||
await user.click(screen.getByText('Mapbox GL'));
|
||||
|
||||
const preview = () => screen.getByTestId('gl-preview');
|
||||
expect(preview()).toHaveAttribute('data-3d', 'true');
|
||||
expect(preview()).toHaveAttribute('data-quality', 'false');
|
||||
|
||||
await user.click(toggleFor('3D Buildings & Terrain'));
|
||||
expect(preview()).toHaveAttribute('data-3d', 'false');
|
||||
|
||||
await user.click(toggleFor('High Quality Mode'));
|
||||
expect(preview()).toHaveAttribute('data-quality', 'true');
|
||||
});
|
||||
|
||||
it('FE-COMP-MAP-027: saving under Mapbox writes the mapbox_style slot', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateSettings = vi.fn().mockResolvedValue(undefined);
|
||||
seedStore(useSettingsStore, { settings: buildSettings(), updateSettings });
|
||||
render(<MapSettingsTab />);
|
||||
|
||||
await user.click(screen.getByText('Mapbox GL'));
|
||||
await user.click(screen.getByText('Save Map'));
|
||||
|
||||
expect(updateSettings).toHaveBeenCalledWith(expect.objectContaining({
|
||||
map_provider: 'mapbox-gl',
|
||||
mapbox_style: MAPBOX_STANDARD,
|
||||
}));
|
||||
expect(updateSettings.mock.calls[0][0]).not.toHaveProperty('maplibre_style');
|
||||
});
|
||||
|
||||
it('FE-COMP-MAP-028: saving under MapLibre writes the maplibre_style slot instead', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateSettings = vi.fn().mockResolvedValue(undefined);
|
||||
seedStore(useSettingsStore, { settings: buildSettings(), updateSettings });
|
||||
render(<MapSettingsTab />);
|
||||
|
||||
await user.click(screen.getByText('MapLibre GL'));
|
||||
await user.click(screen.getByText('Save Map'));
|
||||
|
||||
expect(updateSettings).toHaveBeenCalledWith(expect.objectContaining({
|
||||
map_provider: 'maplibre-gl',
|
||||
maplibre_style: OFM_LIBERTY,
|
||||
}));
|
||||
expect(updateSettings.mock.calls[0][0]).not.toHaveProperty('mapbox_style');
|
||||
});
|
||||
|
||||
it('FE-COMP-MAP-029: a stored GL provider is restored from the settings', () => {
|
||||
seedStore(useSettingsStore, {
|
||||
settings: buildSettings({
|
||||
map_provider: 'maplibre-gl',
|
||||
maplibre_style: 'https://tiles.openfreemap.org/styles/bright',
|
||||
}),
|
||||
});
|
||||
render(<MapSettingsTab />);
|
||||
|
||||
expect(screen.getByDisplayValue('https://tiles.openfreemap.org/styles/bright')).toBeInTheDocument();
|
||||
expect(within(styleDropdown()).getByText('OpenFreeMap Bright')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-MAP-030: picking a Leaflet template fills the tile URL input', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<MapSettingsTab />);
|
||||
|
||||
await user.click(screen.getByText('Select template...'));
|
||||
await user.click(await screen.findByText('CartoDB Dark'));
|
||||
|
||||
expect(screen.getByDisplayValue('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
// FE-COMP-GLPREVIEW-001 to FE-COMP-GLPREVIEW-014
|
||||
import { render, screen, act } from '../../../tests/helpers/render';
|
||||
|
||||
type ClickHandler = (e: { lngLat: { lat: number; lng: number } }) => void;
|
||||
|
||||
const glHandlers = vi.hoisted(() => ({
|
||||
load: undefined as (() => void) | undefined,
|
||||
click: undefined as ClickHandler | undefined,
|
||||
reset() {
|
||||
this.load = undefined;
|
||||
this.click = undefined;
|
||||
},
|
||||
}));
|
||||
|
||||
const glMap = vi.hoisted(() => ({
|
||||
on: vi.fn((event: string, cb: unknown) => {
|
||||
if (event === 'load') glHandlers.load = cb as () => void;
|
||||
if (event === 'click') glHandlers.click = cb as ClickHandler;
|
||||
}),
|
||||
remove: vi.fn(),
|
||||
jumpTo: vi.fn(),
|
||||
setTerrain: vi.fn(),
|
||||
}));
|
||||
|
||||
const mapboxCtor = vi.hoisted(() => vi.fn(function (_options: Record<string, unknown>) {
|
||||
return glMap;
|
||||
}));
|
||||
const maplibreCtor = vi.hoisted(() => vi.fn(function (_options: Record<string, unknown>) {
|
||||
return glMap;
|
||||
}));
|
||||
const mapboxModule = vi.hoisted(() => ({ accessToken: '', Map: mapboxCtor }));
|
||||
|
||||
vi.mock('mapbox-gl', () => ({ default: mapboxModule }));
|
||||
vi.mock('mapbox-gl/dist/mapbox-gl.css', () => ({}));
|
||||
vi.mock('maplibre-gl', () => ({ default: { Map: maplibreCtor } }));
|
||||
vi.mock('maplibre-gl/dist/maplibre-gl.css', () => ({}));
|
||||
|
||||
vi.mock('../Map/mapboxSetup', () => ({
|
||||
isStandardFamily: vi.fn(() => false),
|
||||
supportsCustom3d: vi.fn(() => true),
|
||||
addCustom3dBuildings: vi.fn(),
|
||||
addTerrainAndSky: vi.fn(),
|
||||
}));
|
||||
|
||||
import { isStandardFamily, supportsCustom3d, addCustom3dBuildings, addTerrainAndSky } from '../Map/mapboxSetup';
|
||||
import { MAPBOX_DEFAULT_STYLE, OPENFREEMAP_DEFAULT_STYLE } from '../Map/glProviders';
|
||||
import GlMapPreview from './MapboxPreview';
|
||||
|
||||
const STREETS = 'mapbox://styles/mapbox/streets-v12';
|
||||
|
||||
function mapOptions(ctor: typeof mapboxCtor): Record<string, unknown> {
|
||||
return ctor.mock.calls[0][0] as Record<string, unknown>;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
glHandlers.reset();
|
||||
mapboxModule.accessToken = '';
|
||||
document.documentElement.classList.remove('dark');
|
||||
vi.mocked(isStandardFamily).mockReturnValue(false);
|
||||
vi.mocked(supportsCustom3d).mockReturnValue(true);
|
||||
});
|
||||
|
||||
describe('GlMapPreview', () => {
|
||||
it('FE-COMP-GLPREVIEW-001: without a Mapbox token it shows the hint instead of a map', () => {
|
||||
render(<GlMapPreview token="" style={STREETS} lat={48.8} lng={2.3} zoom={16} enable3d={false} />);
|
||||
|
||||
expect(screen.getByText('Enter a Mapbox access token to preview')).toBeInTheDocument();
|
||||
expect(mapboxCtor).not.toHaveBeenCalled();
|
||||
expect(glMap.jumpTo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-GLPREVIEW-002: a token creates a Mapbox map centred on the given coordinates', () => {
|
||||
render(<GlMapPreview token="pk.test" style={STREETS} lat={48.8566} lng={2.3522} zoom={16} enable3d={false} />);
|
||||
|
||||
expect(mapboxModule.accessToken).toBe('pk.test');
|
||||
expect(mapboxCtor).toHaveBeenCalledTimes(1);
|
||||
expect(mapOptions(mapboxCtor)).toMatchObject({
|
||||
style: STREETS,
|
||||
center: [2.3522, 48.8566],
|
||||
zoom: 16,
|
||||
pitch: 0,
|
||||
antialias: false,
|
||||
projection: 'mercator',
|
||||
});
|
||||
expect(screen.queryByText('Enter a Mapbox access token to preview')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-GLPREVIEW-003: 3D pitches the camera on mount', () => {
|
||||
render(<GlMapPreview token="pk.test" style={STREETS} lat={48.8} lng={2.3} zoom={16} enable3d />);
|
||||
|
||||
expect(mapOptions(mapboxCtor).pitch).toBe(45);
|
||||
});
|
||||
|
||||
it('FE-COMP-GLPREVIEW-004: quality mode enables the globe projection and antialiasing', () => {
|
||||
render(<GlMapPreview token="pk.test" style={STREETS} lat={48.8} lng={2.3} zoom={16} enable3d={false} quality />);
|
||||
|
||||
expect(mapOptions(mapboxCtor)).toMatchObject({ projection: 'globe', antialias: true });
|
||||
});
|
||||
|
||||
it('FE-COMP-GLPREVIEW-005: MapLibre needs no token and never asks for a projection', () => {
|
||||
render(
|
||||
<GlMapPreview
|
||||
provider="maplibre-gl"
|
||||
style={OPENFREEMAP_DEFAULT_STYLE}
|
||||
lat={48.8}
|
||||
lng={2.3}
|
||||
zoom={16}
|
||||
enable3d
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(maplibreCtor).toHaveBeenCalledTimes(1);
|
||||
expect(mapboxCtor).not.toHaveBeenCalled();
|
||||
const opts = mapOptions(maplibreCtor);
|
||||
expect(opts).toMatchObject({ aroundCenter: false, style: OPENFREEMAP_DEFAULT_STYLE, pitch: 0 });
|
||||
expect(opts).not.toHaveProperty('projection');
|
||||
});
|
||||
|
||||
it('FE-COMP-GLPREVIEW-006: a Mapbox style is coerced to the OpenFreeMap default under MapLibre', () => {
|
||||
render(<GlMapPreview provider="maplibre-gl" style={STREETS} lat={48.8} lng={2.3} zoom={16} enable3d={false} />);
|
||||
|
||||
expect(mapOptions(maplibreCtor).style).toBe(OPENFREEMAP_DEFAULT_STYLE);
|
||||
});
|
||||
|
||||
it('FE-COMP-GLPREVIEW-007: loading a 3D-capable custom style adds terrain and buildings', () => {
|
||||
render(<GlMapPreview token="pk.test" style={STREETS} lat={48.8} lng={2.3} zoom={16} enable3d />);
|
||||
act(() => glHandlers.load?.());
|
||||
|
||||
expect(addTerrainAndSky).toHaveBeenCalledWith(glMap);
|
||||
expect(addCustom3dBuildings).toHaveBeenCalledWith(glMap, false);
|
||||
expect(glMap.setTerrain).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-GLPREVIEW-008: dark mode is passed through to the 3D building colours', () => {
|
||||
document.documentElement.classList.add('dark');
|
||||
render(<GlMapPreview token="pk.test" style={STREETS} lat={48.8} lng={2.3} zoom={16} enable3d />);
|
||||
act(() => glHandlers.load?.());
|
||||
|
||||
expect(addCustom3dBuildings).toHaveBeenCalledWith(glMap, true);
|
||||
});
|
||||
|
||||
it('FE-COMP-GLPREVIEW-009: a Standard-family style skips terrain and the custom building layer', () => {
|
||||
vi.mocked(isStandardFamily).mockReturnValue(true);
|
||||
vi.mocked(supportsCustom3d).mockReturnValue(false);
|
||||
render(<GlMapPreview token="pk.test" style={MAPBOX_DEFAULT_STYLE} lat={48.8} lng={2.3} zoom={16} enable3d />);
|
||||
act(() => glHandlers.load?.());
|
||||
|
||||
expect(addTerrainAndSky).not.toHaveBeenCalled();
|
||||
expect(addCustom3dBuildings).not.toHaveBeenCalled();
|
||||
// The default style ships its own terrain, so the preview clears ours.
|
||||
expect(glMap.setTerrain).toHaveBeenCalledWith(null);
|
||||
});
|
||||
|
||||
it('FE-COMP-GLPREVIEW-010: a failing setTerrain on load is swallowed', () => {
|
||||
glMap.setTerrain.mockImplementationOnce(() => {
|
||||
throw new Error('no terrain');
|
||||
});
|
||||
render(<GlMapPreview token="pk.test" style={MAPBOX_DEFAULT_STYLE} lat={48.8} lng={2.3} zoom={16} enable3d={false} />);
|
||||
|
||||
expect(() => act(() => glHandlers.load?.())).not.toThrow();
|
||||
});
|
||||
|
||||
it('FE-COMP-GLPREVIEW-011: with 3D off nothing is added on load', () => {
|
||||
render(<GlMapPreview token="pk.test" style={STREETS} lat={48.8} lng={2.3} zoom={16} enable3d={false} />);
|
||||
act(() => glHandlers.load?.());
|
||||
|
||||
expect(addTerrainAndSky).not.toHaveBeenCalled();
|
||||
expect(addCustom3dBuildings).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-GLPREVIEW-012: a map click reports the picked coordinates', () => {
|
||||
const onClick = vi.fn();
|
||||
render(<GlMapPreview token="pk.test" style={STREETS} lat={48.8} lng={2.3} zoom={16} enable3d={false} onClick={onClick} />);
|
||||
|
||||
act(() => glHandlers.click?.({ lngLat: { lat: 51.5, lng: -0.12 } }));
|
||||
|
||||
expect(onClick).toHaveBeenCalledWith({ lat: 51.5, lng: -0.12 });
|
||||
});
|
||||
|
||||
it('FE-COMP-GLPREVIEW-013: moving the centre recenters instead of rebuilding the map', () => {
|
||||
const { rerender } = render(
|
||||
<GlMapPreview token="pk.test" style={STREETS} lat={48.8} lng={2.3} zoom={16} enable3d={false} />,
|
||||
);
|
||||
glMap.jumpTo.mockClear();
|
||||
|
||||
rerender(<GlMapPreview token="pk.test" style={STREETS} lat={51.5} lng={-0.12} zoom={12} enable3d={false} />);
|
||||
|
||||
expect(glMap.jumpTo).toHaveBeenCalledWith({ center: [-0.12, 51.5], zoom: 12 });
|
||||
expect(mapboxCtor).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-GLPREVIEW-014: a failing jumpTo is swallowed and unmounting removes the map', () => {
|
||||
glMap.jumpTo.mockImplementationOnce(() => {
|
||||
throw new Error('not ready');
|
||||
});
|
||||
const { unmount } = render(
|
||||
<GlMapPreview token="pk.test" style={STREETS} lat={48.8} lng={2.3} zoom={16} enable3d={false} />,
|
||||
);
|
||||
|
||||
expect(glMap.jumpTo).toHaveBeenCalled();
|
||||
glMap.remove.mockImplementationOnce(() => {
|
||||
throw new Error('already gone');
|
||||
});
|
||||
expect(() => unmount()).not.toThrow();
|
||||
expect(glMap.remove).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
// FE-COMP-NAVPREVIEW-001 to FE-COMP-NAVPREVIEW-006
|
||||
import { render, screen } from '../../../tests/helpers/render';
|
||||
import { LayoutGrid, CalendarDays, Globe, Compass } from 'lucide-react';
|
||||
import type { NavItemDef } from '../Layout/navItems';
|
||||
import MobileNavPreview from './MobileNavPreview';
|
||||
|
||||
const DASHBOARD: NavItemDef = { id: 'dashboard', to: '/dashboard', label: 'My Trips', icon: LayoutGrid, pinned: true };
|
||||
const VACAY: NavItemDef = { id: 'vacay', to: '/vacay', label: 'Vacay', icon: CalendarDays };
|
||||
const ATLAS: NavItemDef = { id: 'atlas', to: '/atlas', label: 'Atlas', icon: Globe };
|
||||
const JOURNEY: NavItemDef = { id: 'journey', to: '/journey', label: 'Journey', icon: Compass };
|
||||
|
||||
/** The dock's circles in DOM order, identified by their title attribute. */
|
||||
function slots(container: HTMLElement): string[] {
|
||||
return Array.from(container.querySelectorAll('span[title]')).map(el => el.getAttribute('title') ?? '');
|
||||
}
|
||||
|
||||
describe('MobileNavPreview', () => {
|
||||
it('FE-COMP-NAVPREVIEW-001: renders a circle per bar item plus the More slot', () => {
|
||||
const { container } = render(
|
||||
<MobileNavPreview bar={[DASHBOARD, VACAY, ATLAS]} hasMore moreLabel="More" />,
|
||||
);
|
||||
|
||||
expect(slots(container)).toEqual(['My Trips', 'Vacay', 'Atlas', 'More']);
|
||||
expect(screen.getByTitle('Vacay')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-NAVPREVIEW-002: the More circle is dropped when nothing is demoted', () => {
|
||||
const { container } = render(<MobileNavPreview bar={[DASHBOARD, VACAY]} hasMore={false} moreLabel="More" />);
|
||||
|
||||
expect(slots(container)).toEqual(['My Trips', 'Vacay']);
|
||||
expect(screen.queryByTitle('More')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-NAVPREVIEW-003: the raised centre button splits the slots evenly around it', () => {
|
||||
const { container } = render(
|
||||
<MobileNavPreview bar={[DASHBOARD, VACAY, ATLAS]} hasMore moreLabel="More" />,
|
||||
);
|
||||
|
||||
const row = container.firstElementChild as HTMLElement;
|
||||
const children = Array.from(row.children);
|
||||
// 4 slots → 2 on the left, then the "+", then the rest.
|
||||
const centre = children.findIndex(c => !c.hasAttribute('title'));
|
||||
expect(centre).toBe(2);
|
||||
expect(children).toHaveLength(5);
|
||||
});
|
||||
|
||||
it('FE-COMP-NAVPREVIEW-004: an odd slot count keeps the extra circle on the left', () => {
|
||||
const { container } = render(
|
||||
<MobileNavPreview bar={[DASHBOARD, VACAY, ATLAS, JOURNEY]} hasMore={false} moreLabel="More" />,
|
||||
);
|
||||
|
||||
const children = Array.from((container.firstElementChild as HTMLElement).children);
|
||||
const centre = children.findIndex(c => !c.hasAttribute('title'));
|
||||
expect(centre).toBe(2);
|
||||
expect(slots(container)).toEqual(['My Trips', 'Vacay', 'Atlas', 'Journey']);
|
||||
});
|
||||
|
||||
it('FE-COMP-NAVPREVIEW-005: an empty bar still renders the centre action', () => {
|
||||
const { container } = render(<MobileNavPreview bar={[]} hasMore={false} moreLabel="More" />);
|
||||
|
||||
expect(slots(container)).toEqual([]);
|
||||
expect((container.firstElementChild as HTMLElement).children).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-NAVPREVIEW-006: the More label comes from the caller', () => {
|
||||
render(<MobileNavPreview bar={[DASHBOARD]} hasMore moreLabel="Mehr" />);
|
||||
|
||||
expect(screen.getByTitle('Mehr')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -851,3 +851,284 @@ describe('NotificationsTab — plugin channels', () => {
|
||||
expect(screen.queryByText('Gotify')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Ntfy credentials, webhook edge cases and channel-test failures (015–029)
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const ntfyMatrix = {
|
||||
preferences: { trip_invite: { inapp: true, ntfy: true } },
|
||||
channels: [
|
||||
{ id: 'inapp', source: 'builtin', labelKey: 'settings.notificationPreferences.inapp', active: true, configured: true },
|
||||
{ id: 'ntfy', source: 'builtin', labelKey: 'settings.notificationPreferences.ntfy', active: true, configured: true },
|
||||
],
|
||||
event_types: ['trip_invite'],
|
||||
implemented_combos: { trip_invite: ['inapp', 'ntfy'] },
|
||||
defaults: { ntfyServer: 'https://ntfy.example.org' },
|
||||
};
|
||||
|
||||
const webhookMatrix = {
|
||||
preferences: { trip_invite: { inapp: true, webhook: true } },
|
||||
channels: [
|
||||
{ id: 'inapp', source: 'builtin', labelKey: 'settings.notificationPreferences.inapp', active: true, configured: true },
|
||||
{ id: 'webhook', source: 'builtin', labelKey: 'settings.notificationPreferences.webhook', active: true, configured: true },
|
||||
],
|
||||
event_types: ['trip_invite'],
|
||||
implemented_combos: { trip_invite: ['inapp', 'webhook'] },
|
||||
};
|
||||
|
||||
function mockNtfy(settings: Record<string, unknown> = {}) {
|
||||
server.use(
|
||||
http.get('*/api/notifications/preferences', () => HttpResponse.json(ntfyMatrix)),
|
||||
http.get('*/api/settings', () => HttpResponse.json({ settings })),
|
||||
);
|
||||
}
|
||||
|
||||
function tokenInput(): HTMLInputElement {
|
||||
return document.querySelector('input[type="password"]') as HTMLInputElement;
|
||||
}
|
||||
|
||||
describe('NotificationsTab — ntfy credentials', () => {
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
seedStore(useAuthStore, { isAuthenticated: true, user: buildUser() });
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-015: a stored token is masked and the server default fills the placeholder', async () => {
|
||||
mockNtfy({ ntfy_topic: 'alerts', ntfy_token: '••••••••' });
|
||||
render(<NotificationsTab />);
|
||||
|
||||
expect(await screen.findByDisplayValue('alerts')).toBeInTheDocument();
|
||||
expect(tokenInput()).toHaveValue('');
|
||||
expect(tokenInput()).toHaveAttribute('placeholder', '••••••••');
|
||||
expect(screen.getByPlaceholderText('https://ntfy.example.org')).toHaveValue('');
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-016: saving sends topic and server but omits the untouched token', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: { settings: Record<string, unknown> } | null = null;
|
||||
mockNtfy({ ntfy_topic: 'alerts', ntfy_token: '••••••••' });
|
||||
server.use(
|
||||
http.post('*/api/settings/bulk', async ({ request }) => {
|
||||
body = (await request.json()) as { settings: Record<string, unknown> };
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
render(<><NotificationsTab /><ToastContainer /></>);
|
||||
|
||||
await user.type(await screen.findByPlaceholderText('https://ntfy.example.org'), 'https://ntfy.self.host');
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
|
||||
await screen.findByText('Ntfy settings saved');
|
||||
expect(body!.settings).toEqual({ ntfy_topic: 'alerts', ntfy_server: 'https://ntfy.self.host' });
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-017: a freshly typed token is sent and switches the field to masked', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: { settings: Record<string, unknown> } | null = null;
|
||||
mockNtfy({ ntfy_topic: 'alerts' });
|
||||
server.use(
|
||||
http.post('*/api/settings/bulk', async ({ request }) => {
|
||||
body = (await request.json()) as { settings: Record<string, unknown> };
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
render(<NotificationsTab />);
|
||||
|
||||
await screen.findByDisplayValue('alerts');
|
||||
await user.type(tokenInput(), 'tk_secret');
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
|
||||
await waitFor(() => expect(body!.settings).toMatchObject({ ntfy_token: 'tk_secret' }));
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Clear' })).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-018: a failing ntfy save toasts the generic error', async () => {
|
||||
const user = userEvent.setup();
|
||||
mockNtfy({ ntfy_topic: 'alerts' });
|
||||
server.use(
|
||||
http.post('*/api/settings/bulk', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
|
||||
);
|
||||
render(<><NotificationsTab /><ToastContainer /></>);
|
||||
|
||||
await screen.findByDisplayValue('alerts');
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
|
||||
await screen.findByText('Error');
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-019: Clear wipes the stored token and hides the button', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: { key: string; value: unknown } | null = null;
|
||||
mockNtfy({ ntfy_topic: 'alerts', ntfy_token: '••••••••' });
|
||||
server.use(
|
||||
http.put('*/api/settings', async ({ request }) => {
|
||||
body = (await request.json()) as { key: string; value: unknown };
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
render(<><NotificationsTab /><ToastContainer /></>);
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Clear' }));
|
||||
|
||||
await screen.findByText('Access token cleared');
|
||||
expect(body).toEqual({ key: 'ntfy_token', value: '' });
|
||||
expect(screen.queryByRole('button', { name: 'Clear' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-020: a failing clear keeps the token and toasts', async () => {
|
||||
const user = userEvent.setup();
|
||||
mockNtfy({ ntfy_topic: 'alerts', ntfy_token: '••••••••' });
|
||||
server.use(
|
||||
http.put('*/api/settings', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),
|
||||
);
|
||||
render(<><NotificationsTab /><ToastContainer /></>);
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Clear' }));
|
||||
|
||||
await screen.findByText('Error');
|
||||
expect(screen.getByRole('button', { name: 'Clear' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-021: a successful test posts topic and server, and never the masked token', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: Record<string, unknown> | null = null;
|
||||
mockNtfy({ ntfy_topic: 'alerts', ntfy_server: 'https://ntfy.sh', ntfy_token: '••••••••' });
|
||||
server.use(
|
||||
http.post('*/api/notifications/test-ntfy', async ({ request }) => {
|
||||
body = (await request.json()) as Record<string, unknown>;
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
render(<><NotificationsTab /><ToastContainer /></>);
|
||||
|
||||
await screen.findByDisplayValue('alerts');
|
||||
await user.click(screen.getByRole('button', { name: 'Test' }));
|
||||
|
||||
await screen.findByText('Test ntfy notification sent successfully');
|
||||
expect(body).toEqual({ topic: 'alerts', server: 'https://ntfy.sh', token: null });
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-022: a refused test shows the message the server returned', async () => {
|
||||
const user = userEvent.setup();
|
||||
mockNtfy({ ntfy_topic: 'alerts' });
|
||||
server.use(
|
||||
http.post('*/api/notifications/test-ntfy', () => HttpResponse.json({ success: false, error: 'Topic not found' })),
|
||||
);
|
||||
render(<><NotificationsTab /><ToastContainer /></>);
|
||||
|
||||
await screen.findByDisplayValue('alerts');
|
||||
await user.click(screen.getByRole('button', { name: 'Test' }));
|
||||
|
||||
await screen.findByText('Topic not found');
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-023: a network error during the test falls back to the generic message', async () => {
|
||||
const user = userEvent.setup();
|
||||
mockNtfy({ ntfy_topic: 'alerts' });
|
||||
server.use(
|
||||
http.post('*/api/notifications/test-ntfy', () => HttpResponse.json({ error: 'down' }, { status: 500 })),
|
||||
);
|
||||
render(<><NotificationsTab /><ToastContainer /></>);
|
||||
|
||||
await screen.findByDisplayValue('alerts');
|
||||
await user.click(screen.getByRole('button', { name: 'Test' }));
|
||||
|
||||
await screen.findByText('Test ntfy notification failed');
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-024: without a topic the test button stays disabled', async () => {
|
||||
mockNtfy({});
|
||||
render(<NotificationsTab />);
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Test' })).toBeDisabled());
|
||||
expect(screen.getByPlaceholderText('my-trek-alerts')).toHaveValue('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('NotificationsTab — webhook and channel-test failures', () => {
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
seedStore(useAuthStore, { isAuthenticated: true, user: buildUser() });
|
||||
server.use(
|
||||
http.get('*/api/notifications/preferences', () => HttpResponse.json(webhookMatrix)),
|
||||
http.get('*/api/settings', () => HttpResponse.json({ settings: { webhook_url: '••••••••' } })),
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-025: saving an empty URL unsets the stored webhook', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: { key: string; value: unknown } | null = null;
|
||||
server.use(
|
||||
http.put('*/api/settings', async ({ request }) => {
|
||||
body = (await request.json()) as { key: string; value: unknown };
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
render(<><NotificationsTab /><ToastContainer /></>);
|
||||
|
||||
const input = await screen.findByRole('textbox');
|
||||
expect(input).toHaveAttribute('placeholder', '••••••••');
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
|
||||
await screen.findByText('Webhook URL saved');
|
||||
expect(body).toEqual({ key: 'webhook_url', value: '' });
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole('textbox')).toHaveAttribute('placeholder', 'https://discord.com/api/webhooks/...'),
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-026: a failing webhook save toasts the generic error', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.put('*/api/settings', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
|
||||
);
|
||||
render(<><NotificationsTab /><ToastContainer /></>);
|
||||
|
||||
await screen.findByRole('textbox');
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
|
||||
await screen.findByText('Error');
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-027: a network error during the webhook test falls back to the generic message', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.post('*/api/notifications/test-webhook', () => HttpResponse.json({ error: 'down' }, { status: 500 })),
|
||||
);
|
||||
render(<><NotificationsTab /><ToastContainer /></>);
|
||||
|
||||
await screen.findByRole('textbox');
|
||||
await user.click(screen.getByRole('button', { name: 'Test' }));
|
||||
|
||||
await screen.findByText('Test webhook failed');
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-028: a refused plugin channel test reports the returned error', async () => {
|
||||
const user = userEvent.setup();
|
||||
mockMatrix(pluginMatrix());
|
||||
server.use(
|
||||
http.post('*/api/notifications/test/:channelId', () =>
|
||||
HttpResponse.json({ success: false, error: 'Gotify rejected the token' }),
|
||||
),
|
||||
);
|
||||
render(<><NotificationsTab /><ToastContainer /></>);
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: /send test/i }));
|
||||
|
||||
await screen.findByText('Gotify rejected the token');
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-029: a plugin channel test that errors out falls back to the generic message', async () => {
|
||||
const user = userEvent.setup();
|
||||
mockMatrix(pluginMatrix());
|
||||
server.use(
|
||||
http.post('*/api/notifications/test/:channelId', () => HttpResponse.json({ error: 'down' }, { status: 500 })),
|
||||
);
|
||||
render(<><NotificationsTab /><ToastContainer /></>);
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: /send test/i }));
|
||||
|
||||
await screen.findByText('Test failed.');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,487 @@
|
||||
// FE-COMP-OFFLINETAB-001 to FE-COMP-OFFLINETAB-024
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { act, render, screen, waitFor, within } from '../../../tests/helpers/render';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { buildTrip, buildUser } from '../../../tests/helpers/factories';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { _resetNetworkMode } from '../../sync/networkMode';
|
||||
import { _resetOfflinePrefs, getOfflinePrefs } from '../../sync/offlinePrefs';
|
||||
import type { QueuedMutation, SyncMeta } from '../../db/offlineDb';
|
||||
import type { PrepareProgress } from '../../sync/tripSyncManager';
|
||||
import type { Trip } from '../../types';
|
||||
import OfflineTab from './OfflineTab';
|
||||
|
||||
// Dexie, the sync manager, the mutation queue and the tile cache are the four
|
||||
// side-effecting neighbours of this tab; network mode, offline prefs and the
|
||||
// trips API run for real.
|
||||
const h = vi.hoisted(() => {
|
||||
const syncMetaToArray = vi.fn();
|
||||
const tripsGet = vi.fn();
|
||||
const tripsToArray = vi.fn();
|
||||
const placeCount = vi.fn();
|
||||
const fileCount = vi.fn();
|
||||
const counted = (fn: (id: number) => Promise<number>) => ({
|
||||
where: () => ({ equals: (id: number) => ({ count: () => fn(id) }) }),
|
||||
});
|
||||
return {
|
||||
syncMetaToArray, tripsGet, tripsToArray, placeCount, fileCount,
|
||||
fakeDb: {
|
||||
syncMeta: { toArray: syncMetaToArray },
|
||||
trips: { get: tripsGet, toArray: tripsToArray },
|
||||
places: counted(placeCount),
|
||||
tripFiles: counted(fileCount),
|
||||
},
|
||||
clearAll: vi.fn(),
|
||||
clearTripData: vi.fn(),
|
||||
prepareForOffline: vi.fn(),
|
||||
syncAll: vi.fn(),
|
||||
pendingCount: vi.fn(),
|
||||
failedCount: vi.fn(),
|
||||
conflicts: vi.fn(),
|
||||
resolveKeepMine: vi.fn(),
|
||||
resolveKeepServer: vi.fn(),
|
||||
clearTileCache: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../../db/offlineDb', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../db/offlineDb')>();
|
||||
return { ...actual, offlineDb: h.fakeDb, clearAll: h.clearAll, clearTripData: h.clearTripData };
|
||||
});
|
||||
|
||||
vi.mock('../../sync/tripSyncManager', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../sync/tripSyncManager')>();
|
||||
return { ...actual, tripSyncManager: { prepareForOffline: h.prepareForOffline, syncAll: h.syncAll } };
|
||||
});
|
||||
|
||||
vi.mock('../../sync/mutationQueue', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../sync/mutationQueue')>();
|
||||
return {
|
||||
...actual,
|
||||
mutationQueue: {
|
||||
pendingCount: h.pendingCount,
|
||||
failedCount: h.failedCount,
|
||||
conflicts: h.conflicts,
|
||||
resolveKeepMine: h.resolveKeepMine,
|
||||
resolveKeepServer: h.resolveKeepServer,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../../sync/tilePrefetcher', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../sync/tilePrefetcher')>();
|
||||
return { ...actual, clearTileCache: h.clearTileCache };
|
||||
});
|
||||
|
||||
const paris = buildTrip({ id: 1, title: 'Paris', start_date: '2025-06-01', end_date: '2025-06-05' });
|
||||
const tokyo = buildTrip({ id: 2, title: 'Tokyo', start_date: '2025-09-01', end_date: '2025-09-15' });
|
||||
|
||||
const meta = (tripId: number, over: Partial<SyncMeta> = {}): SyncMeta => ({
|
||||
tripId,
|
||||
lastSyncedAt: null,
|
||||
status: 'idle',
|
||||
tilesBbox: null,
|
||||
filesCachedCount: 0,
|
||||
...over,
|
||||
});
|
||||
|
||||
const conflict = (over: Partial<QueuedMutation> = {}): QueuedMutation => ({
|
||||
id: 'c1',
|
||||
tripId: 1,
|
||||
method: 'PUT',
|
||||
url: '/trips/1/places/9',
|
||||
body: { name: 'Louvre' },
|
||||
createdAt: 0,
|
||||
status: 'conflict',
|
||||
attempts: 1,
|
||||
lastError: null,
|
||||
...over,
|
||||
});
|
||||
|
||||
/** Seed the Dexie cache with the given (trip, meta) pairs. */
|
||||
function cache(rows: { trip: Trip; meta?: Partial<SyncMeta>; places?: number; files?: number }[]): void {
|
||||
h.syncMetaToArray.mockResolvedValue(rows.map(r => meta(r.trip.id, r.meta)));
|
||||
h.tripsGet.mockImplementation(async (id: number) => rows.find(r => r.trip.id === id)?.trip);
|
||||
h.placeCount.mockImplementation(async (id: number) => rows.find(r => r.trip.id === id)?.places ?? 0);
|
||||
h.fileCount.mockImplementation(async (id: number) => rows.find(r => r.trip.id === id)?.files ?? 0);
|
||||
}
|
||||
|
||||
function setOnLine(value: boolean): void {
|
||||
Object.defineProperty(window.navigator, 'onLine', { value, configurable: true });
|
||||
}
|
||||
|
||||
/** The Section wrapper card that carries the given heading. */
|
||||
const card = (title: string) => screen.getByText(title).closest('div.rounded-xl') as HTMLElement;
|
||||
|
||||
/** The Stat tile that carries the given label. */
|
||||
const stat = (label: string) => screen.getByText(label).parentElement as HTMLElement;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
resetAllStores();
|
||||
_resetNetworkMode();
|
||||
_resetOfflinePrefs();
|
||||
setOnLine(true);
|
||||
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });
|
||||
|
||||
h.syncMetaToArray.mockResolvedValue([]);
|
||||
h.tripsGet.mockResolvedValue(undefined);
|
||||
h.tripsToArray.mockResolvedValue([]);
|
||||
h.placeCount.mockResolvedValue(0);
|
||||
h.fileCount.mockResolvedValue(0);
|
||||
h.pendingCount.mockResolvedValue(0);
|
||||
h.failedCount.mockResolvedValue(0);
|
||||
h.conflicts.mockResolvedValue([]);
|
||||
h.clearAll.mockResolvedValue(undefined);
|
||||
h.clearTripData.mockResolvedValue(undefined);
|
||||
h.clearTileCache.mockResolvedValue(undefined);
|
||||
h.prepareForOffline.mockResolvedValue(undefined);
|
||||
h.syncAll.mockResolvedValue(undefined);
|
||||
h.resolveKeepMine.mockResolvedValue(undefined);
|
||||
h.resolveKeepServer.mockResolvedValue(undefined);
|
||||
|
||||
server.use(http.get('/api/trips', () => HttpResponse.json({ trips: [paris, tokyo] })));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setOnLine(true);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('OfflineTab', () => {
|
||||
it('FE-COMP-OFFLINETAB-001: shows the loading line while the cache is being read', () => {
|
||||
h.syncMetaToArray.mockReturnValue(new Promise(() => {}));
|
||||
render(<OfflineTab />);
|
||||
|
||||
expect(screen.getByText('Loading…')).toBeInTheDocument();
|
||||
expect(screen.getByText('Offline mode')).toBeInTheDocument();
|
||||
expect(screen.queryByText('No trips cached yet. Connect to the internet to sync.')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-002: an empty cache reports zero stats and disables Clear cache', async () => {
|
||||
render(<OfflineTab />);
|
||||
|
||||
expect(await screen.findByText('No trips cached yet. Connect to the internet to sync.')).toBeInTheDocument();
|
||||
expect(within(stat('Cached trips')).getByText('0')).toBeInTheDocument();
|
||||
expect(within(stat('Pending changes')).getByText('0')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Clear cache' })).toBeDisabled();
|
||||
expect(screen.queryByText('Failed changes')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Conflicts')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Sync conflicts')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-003: cached trips are listed oldest first with their place and file counts', async () => {
|
||||
cache([
|
||||
{ trip: tokyo, places: 3, files: 1 },
|
||||
{ trip: paris, places: 7, files: 2 },
|
||||
]);
|
||||
render(<OfflineTab />);
|
||||
|
||||
const cacheCard = card('Offline cache');
|
||||
await waitFor(() => expect(within(cacheCard).getByText('Paris')).toBeInTheDocument());
|
||||
const titles = within(cacheCard).getAllByText(/^(Paris|Tokyo)$/).map(el => el.textContent);
|
||||
expect(titles).toEqual(['Paris', 'Tokyo']);
|
||||
expect(within(cacheCard).getByText(/Jun 1, 2025 – Jun 5, 2025/)).toHaveTextContent('7');
|
||||
expect(within(cacheCard).getByText(/Sep 1, 2025 – Sep 15, 2025/)).toHaveTextContent('3');
|
||||
expect(within(stat('Cached trips')).getByText('2')).toBeInTheDocument();
|
||||
// Never synced → the time column shows a dash.
|
||||
expect(within(cacheCard).getAllByText('—')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-004: a trip without dates renders dashes instead of a range', async () => {
|
||||
cache([{ trip: buildTrip({ id: 3, title: 'Someday', start_date: null, end_date: null }) }]);
|
||||
render(<OfflineTab />);
|
||||
|
||||
const cacheCard = card('Offline cache');
|
||||
await waitFor(() => expect(within(cacheCard).getByText('Someday')).toBeInTheDocument());
|
||||
expect(within(cacheCard).getByText(/— – —/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-005: a sync-meta row without its trip in Dexie is dropped', async () => {
|
||||
h.syncMetaToArray.mockResolvedValue([meta(1), meta(99)]);
|
||||
h.tripsGet.mockImplementation(async (id: number) => (id === 1 ? paris : undefined));
|
||||
render(<OfflineTab />);
|
||||
|
||||
const cacheCard = card('Offline cache');
|
||||
await waitFor(() => expect(within(cacheCard).getByText('Paris')).toBeInTheDocument());
|
||||
expect(within(stat('Cached trips')).getByText('1')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-006: a synced trip shows its last sync time instead of a dash', async () => {
|
||||
const at = new Date('2025-06-02T09:30:00Z').getTime();
|
||||
cache([{ trip: paris, meta: { lastSyncedAt: at } }]);
|
||||
render(<OfflineTab />);
|
||||
|
||||
const cacheCard = card('Offline cache');
|
||||
await waitFor(() => expect(within(cacheCard).getByText('Paris')).toBeInTheDocument());
|
||||
const expected = new Date(at).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
|
||||
expect(within(cacheCard).getByText(expected)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-007: pending, failed and conflict counters only appear when they are non-zero', async () => {
|
||||
h.pendingCount.mockResolvedValue(4);
|
||||
h.failedCount.mockResolvedValue(2);
|
||||
h.conflicts.mockResolvedValue([conflict()]);
|
||||
render(<OfflineTab />);
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Failed changes')).toBeInTheDocument());
|
||||
expect(within(stat('Pending changes')).getByText('4')).toBeInTheDocument();
|
||||
expect(within(stat('Failed changes')).getByText('2')).toBeInTheDocument();
|
||||
expect(within(stat('Conflicts')).getByText('1')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-008: conflicts are named from the queued body, the server copy or the entity id', async () => {
|
||||
h.conflicts.mockResolvedValue([
|
||||
conflict({ id: 'a', body: { name: 'Louvre' } }),
|
||||
conflict({ id: 'b', body: {}, conflictServer: { name: 'Server name' } }),
|
||||
conflict({ id: 'c', body: {}, entityId: 42 }),
|
||||
]);
|
||||
render(<OfflineTab />);
|
||||
|
||||
await screen.findByText('Sync conflicts');
|
||||
expect(screen.getByText(/Louvre/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Server name/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/#42/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-009: keep-mine and keep-theirs resolve the right conflict and reload', async () => {
|
||||
const user = userEvent.setup();
|
||||
h.conflicts.mockResolvedValue([conflict({ id: 'a' }), conflict({ id: 'b', body: { name: 'Eiffel' } })]);
|
||||
render(<OfflineTab />);
|
||||
|
||||
const row = (await screen.findByText(/Eiffel/)).parentElement as HTMLElement;
|
||||
await user.click(within(row).getByRole('button', { name: 'Keep mine' }));
|
||||
expect(h.resolveKeepMine).toHaveBeenCalledWith('b');
|
||||
expect(h.resolveKeepServer).not.toHaveBeenCalled();
|
||||
|
||||
await user.click(within(row).getByRole('button', { name: 'Keep theirs' }));
|
||||
expect(h.resolveKeepServer).toHaveBeenCalledWith('b');
|
||||
// Both resolutions re-read the cache (once on mount + once per resolution).
|
||||
await waitFor(() => expect(h.conflicts).toHaveBeenCalledTimes(3));
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-010: the conflict strategy select persists the choice', async () => {
|
||||
const user = userEvent.setup();
|
||||
h.conflicts.mockResolvedValue([conflict()]);
|
||||
render(<OfflineTab />);
|
||||
|
||||
await screen.findByText('When a conflict happens');
|
||||
const select = screen.getByRole('combobox') as HTMLSelectElement;
|
||||
expect(select.value).toBe('ask');
|
||||
|
||||
await user.selectOptions(select, 'server');
|
||||
expect(getOfflinePrefs().conflictStrategy).toBe('server');
|
||||
await waitFor(() => expect(select.value).toBe('server'));
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-011: Prepare renders live progress and the done marker', async () => {
|
||||
const user = userEvent.setup();
|
||||
let release!: () => void;
|
||||
h.prepareForOffline.mockImplementation(async (cb: (p: PrepareProgress) => void) => {
|
||||
cb({ phase: 'files', current: 1, total: 4, label: 'Paris' });
|
||||
await new Promise<void>(resolve => { release = resolve; });
|
||||
cb({ phase: 'done', current: 4, total: 4 });
|
||||
});
|
||||
render(<OfflineTab />);
|
||||
|
||||
await screen.findByText('No trips cached yet. Connect to the internet to sync.');
|
||||
await user.click(screen.getByRole('button', { name: 'Download for offline use' }));
|
||||
|
||||
expect(await screen.findByText('Documents · 1/4 · Paris')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Downloading…' })).toBeDisabled();
|
||||
|
||||
await act(async () => { release(); });
|
||||
expect(await screen.findByText('Ready for offline use')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Download for offline use' })).toBeEnabled();
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-012: a progress report without a total renders a full bar', async () => {
|
||||
const user = userEvent.setup();
|
||||
let release!: () => void;
|
||||
h.prepareForOffline.mockImplementation(async (cb: (p: PrepareProgress) => void) => {
|
||||
cb({ phase: 'tiles', current: 0, total: 0 });
|
||||
await new Promise<void>(resolve => { release = resolve; });
|
||||
});
|
||||
render(<OfflineTab />);
|
||||
|
||||
await screen.findByText('No trips cached yet. Connect to the internet to sync.');
|
||||
await user.click(screen.getByRole('button', { name: 'Download for offline use' }));
|
||||
|
||||
const label = await screen.findByText('Map tiles · 0/0');
|
||||
const bar = label.previousElementSibling?.firstElementChild as HTMLElement;
|
||||
expect(bar).toHaveStyle({ width: '100%' });
|
||||
await act(async () => { release(); });
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-013: a half-finished trips phase renders a proportional bar', async () => {
|
||||
const user = userEvent.setup();
|
||||
let release!: () => void;
|
||||
h.prepareForOffline.mockImplementation(async (cb: (p: PrepareProgress) => void) => {
|
||||
cb({ phase: 'trips', current: 1, total: 4 });
|
||||
await new Promise<void>(resolve => { release = resolve; });
|
||||
});
|
||||
render(<OfflineTab />);
|
||||
|
||||
await screen.findByText('No trips cached yet. Connect to the internet to sync.');
|
||||
await user.click(screen.getByRole('button', { name: 'Download for offline use' }));
|
||||
|
||||
const label = await screen.findByText('Trip data · 1/4');
|
||||
const bar = label.previousElementSibling?.firstElementChild as HTMLElement;
|
||||
expect(bar).toHaveStyle({ width: '25%' });
|
||||
await act(async () => { release(); });
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-014: forcing offline downloads first, then engages and locks the actions', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<OfflineTab />);
|
||||
|
||||
await screen.findByText('No trips cached yet. Connect to the internet to sync.');
|
||||
await user.click(screen.getByRole('button', { name: 'Force offline mode' }));
|
||||
|
||||
expect(h.prepareForOffline).toHaveBeenCalledTimes(1);
|
||||
expect(await screen.findByText(/Offline mode is on/)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Download for offline use' })).toBeDisabled();
|
||||
expect(screen.getByRole('button', { name: 'Re-sync now' })).toBeDisabled();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Force offline mode' }));
|
||||
await waitFor(() => expect(screen.queryByText(/Offline mode is on/)).not.toBeInTheDocument());
|
||||
expect(screen.getByRole('button', { name: 'Re-sync now' })).toBeEnabled();
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-015: forcing offline while already disconnected skips the download', async () => {
|
||||
const user = userEvent.setup();
|
||||
setOnLine(false);
|
||||
render(<OfflineTab />);
|
||||
|
||||
await screen.findByText('No trips cached yet. Connect to the internet to sync.');
|
||||
expect(screen.getByRole('button', { name: 'Download for offline use' })).toBeDisabled();
|
||||
await user.click(screen.getByRole('button', { name: 'Force offline mode' }));
|
||||
|
||||
expect(h.prepareForOffline).not.toHaveBeenCalled();
|
||||
expect(await screen.findByText(/Offline mode is on/)).toBeInTheDocument();
|
||||
// Offline, the trip list comes out of Dexie instead of the API.
|
||||
expect(h.tripsToArray).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-016: Re-sync runs syncAll and re-reads the cache', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<OfflineTab />);
|
||||
|
||||
await screen.findByText('No trips cached yet. Connect to the internet to sync.');
|
||||
await user.click(screen.getByRole('button', { name: 'Re-sync now' }));
|
||||
|
||||
expect(h.syncAll).toHaveBeenCalledTimes(1);
|
||||
await waitFor(() => expect(h.syncMetaToArray).toHaveBeenCalledTimes(2));
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-017: Re-sync shows the syncing label while it runs', async () => {
|
||||
const user = userEvent.setup();
|
||||
let release!: () => void;
|
||||
h.syncAll.mockImplementation(() => new Promise<void>(resolve => { release = resolve; }));
|
||||
render(<OfflineTab />);
|
||||
|
||||
await screen.findByText('No trips cached yet. Connect to the internet to sync.');
|
||||
await user.click(screen.getByRole('button', { name: 'Re-sync now' }));
|
||||
|
||||
expect(await screen.findByRole('button', { name: 'Syncing…' })).toBeDisabled();
|
||||
await act(async () => { release(); });
|
||||
expect(await screen.findByRole('button', { name: 'Re-sync now' })).toBeEnabled();
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-018: turning map tiles off drops the tile cache, turning them back on does not', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<OfflineTab />);
|
||||
|
||||
const toggle = await screen.findByRole('button', { name: 'Store map tiles offline' });
|
||||
expect(toggle).toHaveAttribute('aria-pressed', 'true');
|
||||
|
||||
await user.click(toggle);
|
||||
expect(getOfflinePrefs().cacheTiles).toBe(false);
|
||||
expect(h.clearTileCache).toHaveBeenCalledTimes(1);
|
||||
await waitFor(() => expect(toggle).toHaveAttribute('aria-pressed', 'false'));
|
||||
|
||||
await user.click(toggle);
|
||||
expect(getOfflinePrefs().cacheTiles).toBe(true);
|
||||
expect(h.clearTileCache).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-019: switching a trip off evicts it, switching it back on re-syncs', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<OfflineTab />);
|
||||
|
||||
const toggle = await screen.findByRole('button', { name: 'Tokyo' });
|
||||
expect(toggle).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(screen.getAllByText('Stored offline')).toHaveLength(2);
|
||||
|
||||
await user.click(toggle);
|
||||
expect(h.clearTripData).toHaveBeenCalledWith(2);
|
||||
await waitFor(() => expect(screen.getByText('Not stored')).toBeInTheDocument());
|
||||
|
||||
await user.click(toggle);
|
||||
await waitFor(() => expect(h.syncAll).toHaveBeenCalledTimes(1));
|
||||
expect(h.clearTripData).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-020: the per-trip section disappears when there are no trips at all', async () => {
|
||||
server.use(http.get('/api/trips', () => HttpResponse.json({ trips: [] })));
|
||||
render(<OfflineTab />);
|
||||
|
||||
await screen.findByText('No trips cached yet. Connect to the internet to sync.');
|
||||
expect(screen.queryByText('Trips')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('Store map tiles offline')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-021: a failing trips API falls back to the Dexie copy', async () => {
|
||||
server.use(http.get('/api/trips', () => HttpResponse.json({ error: 'down' }, { status: 500 })));
|
||||
h.tripsToArray.mockResolvedValue([tokyo, paris]);
|
||||
render(<OfflineTab />);
|
||||
|
||||
await screen.findByRole('button', { name: 'Paris' });
|
||||
// Dexie rows are sorted by start date too.
|
||||
const labels = screen.getAllByRole('button')
|
||||
.map(el => el.getAttribute('aria-label'))
|
||||
.filter((l): l is string => l !== null);
|
||||
expect(labels).toEqual(['Force offline mode', 'Store map tiles offline', 'Paris', 'Tokyo']);
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-022: when both the API and Dexie fail the trip list is simply empty', async () => {
|
||||
server.use(http.get('/api/trips', () => HttpResponse.json({ error: 'down' }, { status: 500 })));
|
||||
h.tripsToArray.mockRejectedValue(new Error('dexie is gone'));
|
||||
render(<OfflineTab />);
|
||||
|
||||
await screen.findByText('No trips cached yet. Connect to the internet to sync.');
|
||||
expect(screen.queryByText('Trips')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-023: Clear cache asks first and a declined confirm keeps the data', async () => {
|
||||
const user = userEvent.setup();
|
||||
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);
|
||||
cache([{ trip: paris }]);
|
||||
render(<OfflineTab />);
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Clear cache' })).toBeEnabled());
|
||||
await user.click(screen.getByRole('button', { name: 'Clear cache' }));
|
||||
|
||||
expect(confirmSpy).toHaveBeenCalledWith('Clear all offline trip data? You can re-sync anytime while online.');
|
||||
expect(h.clearAll).not.toHaveBeenCalled();
|
||||
expect(within(card('Offline cache')).getByText('Paris')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-OFFLINETAB-024: confirming Clear cache wipes the database and reloads', async () => {
|
||||
const user = userEvent.setup();
|
||||
vi.spyOn(window, 'confirm').mockReturnValue(true);
|
||||
cache([{ trip: paris }]);
|
||||
render(<OfflineTab />);
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Clear cache' })).toBeEnabled());
|
||||
h.syncMetaToArray.mockResolvedValue([]);
|
||||
await user.click(screen.getByRole('button', { name: 'Clear cache' }));
|
||||
|
||||
expect(h.clearAll).toHaveBeenCalledTimes(1);
|
||||
await screen.findByText('No trips cached yet. Connect to the internet to sync.');
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Clear cache' })).toBeDisabled());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,400 @@
|
||||
// FE-COMP-PASSKEYS-001 to FE-COMP-PASSKEYS-022
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { render, screen, waitFor, within } from '../../../tests/helpers/render';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { ToastContainer } from '../shared/Toast';
|
||||
import type { PasskeyCredential } from '../../api/client';
|
||||
import PasskeysSection from './PasskeysSection';
|
||||
|
||||
// The WebAuthn ceremony is the one thing jsdom cannot do. @simplewebauthn/browser
|
||||
// is the only caller of navigator.credentials here, so it is stubbed wholesale;
|
||||
// navigator.credentials itself is stubbed too so nothing can slip past.
|
||||
const startRegistration = vi.fn();
|
||||
vi.mock('@simplewebauthn/browser', () => ({
|
||||
startRegistration: (...args: unknown[]) => startRegistration(...args),
|
||||
}));
|
||||
|
||||
const cred = (over: Partial<PasskeyCredential> = {}): PasskeyCredential => ({
|
||||
id: 1,
|
||||
name: 'MacBook',
|
||||
device_type: 'multiDevice',
|
||||
backed_up: true,
|
||||
created_at: '2025-05-01 08:30:00',
|
||||
last_used_at: null,
|
||||
...over,
|
||||
});
|
||||
|
||||
function serve(opts: {
|
||||
credentials?: PasskeyCredential[]
|
||||
passkeyLogin?: boolean
|
||||
passkeyConfigured?: boolean
|
||||
} = {}): void {
|
||||
server.use(
|
||||
http.get('/api/auth/app-config', () => HttpResponse.json({
|
||||
has_users: true,
|
||||
allow_registration: true,
|
||||
demo_mode: false,
|
||||
password_login: true,
|
||||
passkey_login: opts.passkeyLogin ?? true,
|
||||
passkey_configured: opts.passkeyConfigured ?? true,
|
||||
})),
|
||||
http.get('/api/auth/passkey/credentials', () =>
|
||||
HttpResponse.json({ credentials: opts.credentials ?? [] })),
|
||||
);
|
||||
}
|
||||
|
||||
/** The <li> that carries the given credential name. */
|
||||
const item = (name: string) => screen.getByText(name).closest('li') as HTMLElement;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
Object.defineProperty(navigator, 'credentials', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: { create: vi.fn(async () => null), get: vi.fn(async () => null) },
|
||||
});
|
||||
startRegistration.mockResolvedValue({ id: 'cred-id', rawId: 'cred-id', type: 'public-key' });
|
||||
serve();
|
||||
});
|
||||
|
||||
describe('PasskeysSection', () => {
|
||||
it('FE-COMP-PASSKEYS-001: renders nothing in demo mode', () => {
|
||||
const { container } = render(<PasskeysSection demoMode />);
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it('FE-COMP-PASSKEYS-002: renders nothing once loaded when the feature is off and there are no credentials', async () => {
|
||||
serve({ passkeyLogin: false, credentials: [] });
|
||||
const { container } = render(<PasskeysSection />);
|
||||
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement());
|
||||
});
|
||||
|
||||
it('FE-COMP-PASSKEYS-003: keeps the list reachable when the feature is off but credentials exist', async () => {
|
||||
serve({ passkeyLogin: false, credentials: [cred()] });
|
||||
render(<PasskeysSection />);
|
||||
|
||||
expect(await screen.findByText('MacBook')).toBeInTheDocument();
|
||||
expect(screen.getByText('Passkeys')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Add a passkey' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PASSKEYS-004: warns when the feature is on but the server has no RP ID', async () => {
|
||||
serve({ passkeyLogin: true, passkeyConfigured: false });
|
||||
render(<PasskeysSection />);
|
||||
|
||||
expect(await screen.findByText(/not fully configured on this server/)).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Add a passkey' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PASSKEYS-005: offers the Add action when the feature is on and configured', async () => {
|
||||
render(<PasskeysSection />);
|
||||
|
||||
expect(await screen.findByRole('button', { name: 'Add a passkey' })).toBeInTheDocument();
|
||||
expect(screen.queryByText(/not fully configured on this server/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PASSKEYS-006: a synced credential shows its name, badge, added date and never-used note', async () => {
|
||||
serve({ credentials: [cred()] });
|
||||
render(<PasskeysSection />);
|
||||
|
||||
await screen.findByText('MacBook');
|
||||
const li = item('MacBook');
|
||||
expect(within(li).getByText('Synced')).toBeInTheDocument();
|
||||
expect(within(li).getByText(/Added: 5\/1\/2025/)).toHaveTextContent('Never used');
|
||||
});
|
||||
|
||||
it('FE-COMP-PASSKEYS-007: a device-bound credential without a name falls back to the default label', async () => {
|
||||
serve({ credentials: [cred({ name: null, backed_up: false, last_used_at: '2025-06-10T12:00:00Z' })] });
|
||||
render(<PasskeysSection />);
|
||||
|
||||
await screen.findByText('Passkey');
|
||||
const li = item('Passkey');
|
||||
expect(within(li).getByText('This device')).toBeInTheDocument();
|
||||
expect(within(li).getByText(/Last used: 6\/10\/2025/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PASSKEYS-008: an unparseable timestamp collapses to a dash', async () => {
|
||||
serve({ credentials: [cred({ created_at: 'never' })] });
|
||||
render(<PasskeysSection />);
|
||||
|
||||
await screen.findByText('MacBook');
|
||||
expect(within(item('MacBook')).getByText(/Added: —/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PASSKEYS-009: a failing credential list still renders the section', async () => {
|
||||
server.use(http.get('/api/auth/passkey/credentials', () =>
|
||||
HttpResponse.json({ error: 'boom' }, { status: 500 })));
|
||||
render(<PasskeysSection />);
|
||||
|
||||
expect(await screen.findByRole('button', { name: 'Add a passkey' })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('listitem')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PASSKEYS-010: a failing app-config leaves the feature off', async () => {
|
||||
server.use(
|
||||
http.get('/api/auth/app-config', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
|
||||
http.get('/api/auth/passkey/credentials', () => HttpResponse.json({ credentials: [cred()] })),
|
||||
);
|
||||
render(<PasskeysSection />);
|
||||
|
||||
expect(await screen.findByText('MacBook')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Add a passkey' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PASSKEYS-011: the add form opens, requires a password and closes on Cancel', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<PasskeysSection />);
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Add a passkey' }));
|
||||
expect(screen.getByText('Confirm your current password, then follow your device prompt.')).toBeInTheDocument();
|
||||
// The submit shares its label with the trigger — it is the only one left.
|
||||
expect(screen.getByRole('button', { name: 'Add a passkey' })).toBeDisabled();
|
||||
|
||||
await user.type(screen.getByPlaceholderText('Current password'), 'hunter2');
|
||||
expect(screen.getByRole('button', { name: 'Add a passkey' })).toBeEnabled();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
await waitFor(() => expect(screen.queryByPlaceholderText('Current password')).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('FE-COMP-PASSKEYS-012: adding runs the WebAuthn ceremony and reloads the list', async () => {
|
||||
const user = userEvent.setup();
|
||||
const sent: { body?: { attestationResponse?: { id?: string }; name?: string } } = {};
|
||||
let listCalls = 0;
|
||||
server.use(
|
||||
http.get('/api/auth/passkey/credentials', () => {
|
||||
listCalls += 1;
|
||||
return HttpResponse.json({ credentials: listCalls === 1 ? [] : [cred({ name: 'YubiKey' })] });
|
||||
}),
|
||||
http.post('/api/auth/passkey/register/options', () => HttpResponse.json({ challenge: 'abc' })),
|
||||
http.post('/api/auth/passkey/register/verify', async ({ request }) => {
|
||||
sent.body = await request.json() as { attestationResponse?: { id?: string }; name?: string };
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
render(<><ToastContainer /><PasskeysSection /></>);
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Add a passkey' }));
|
||||
await user.type(screen.getByPlaceholderText('Current password'), 'hunter2');
|
||||
await user.type(screen.getByPlaceholderText(/Name \(optional/), ' YubiKey ');
|
||||
await user.click(screen.getByRole('button', { name: 'Add a passkey' }));
|
||||
|
||||
await screen.findByText('Passkey added');
|
||||
expect(startRegistration).toHaveBeenCalledWith({ optionsJSON: { challenge: 'abc' } });
|
||||
expect(sent.body?.name).toBe('YubiKey');
|
||||
expect(sent.body?.attestationResponse?.id).toBe('cred-id');
|
||||
expect(await screen.findByText('YubiKey')).toBeInTheDocument();
|
||||
// The form closed and reset.
|
||||
expect(screen.queryByPlaceholderText('Current password')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PASSKEYS-013: an empty name is sent as undefined rather than a blank string', async () => {
|
||||
const user = userEvent.setup();
|
||||
const sent: { body?: Record<string, unknown> } = {};
|
||||
server.use(
|
||||
http.post('/api/auth/passkey/register/options', () => HttpResponse.json({ challenge: 'abc' })),
|
||||
http.post('/api/auth/passkey/register/verify', async ({ request }) => {
|
||||
sent.body = await request.json() as Record<string, unknown>;
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
render(<><ToastContainer /><PasskeysSection /></>);
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Add a passkey' }));
|
||||
await user.type(screen.getByPlaceholderText('Current password'), 'hunter2');
|
||||
await user.click(screen.getByRole('button', { name: 'Add a passkey' }));
|
||||
|
||||
await screen.findByText('Passkey added');
|
||||
expect(sent.body).toBeDefined();
|
||||
expect(sent.body).not.toHaveProperty('name');
|
||||
});
|
||||
|
||||
it('FE-COMP-PASSKEYS-014: a cancelled browser prompt reports the cancellation, not an error', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(http.post('/api/auth/passkey/register/options', () => HttpResponse.json({ challenge: 'abc' })));
|
||||
const abort = new Error('user aborted');
|
||||
abort.name = 'NotAllowedError';
|
||||
startRegistration.mockRejectedValue(abort);
|
||||
render(<><ToastContainer /><PasskeysSection /></>);
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Add a passkey' }));
|
||||
await user.type(screen.getByPlaceholderText('Current password'), 'hunter2');
|
||||
await user.click(screen.getByRole('button', { name: 'Add a passkey' }));
|
||||
|
||||
await screen.findByText('Passkey setup cancelled');
|
||||
// The form stays open so the user can retry.
|
||||
expect(screen.getByPlaceholderText('Current password')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PASSKEYS-015: a rejected password surfaces the server message', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(http.post('/api/auth/passkey/register/options', () =>
|
||||
HttpResponse.json({ error: 'Wrong password' }, { status: 401 })));
|
||||
render(<><ToastContainer /><PasskeysSection /></>);
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Add a passkey' }));
|
||||
await user.type(screen.getByPlaceholderText('Current password'), 'nope');
|
||||
await user.click(screen.getByRole('button', { name: 'Add a passkey' }));
|
||||
|
||||
await screen.findByText('Wrong password');
|
||||
expect(startRegistration).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-PASSKEYS-016: renaming sends the trimmed name and refreshes', async () => {
|
||||
const user = userEvent.setup();
|
||||
const sent: { body?: { name?: string } } = {};
|
||||
let listCalls = 0;
|
||||
server.use(
|
||||
http.get('/api/auth/passkey/credentials', () => {
|
||||
listCalls += 1;
|
||||
return HttpResponse.json({ credentials: [cred({ name: listCalls === 1 ? 'MacBook' : 'Work laptop' })] });
|
||||
}),
|
||||
http.patch('/api/auth/passkey/credentials/1', async ({ request }) => {
|
||||
sent.body = await request.json() as { name?: string };
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
render(<><ToastContainer /><PasskeysSection /></>);
|
||||
|
||||
await screen.findByText('MacBook');
|
||||
await user.click(within(item('MacBook')).getByRole('button', { name: 'Rename' }));
|
||||
const input = screen.getByDisplayValue('MacBook');
|
||||
await user.clear(input);
|
||||
await user.type(input, ' Work laptop ');
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
|
||||
await waitFor(() => expect(sent.body).toEqual({ name: 'Work laptop' }));
|
||||
expect(await screen.findByText('Work laptop')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PASSKEYS-017: Enter commits a rename and Escape abandons it', async () => {
|
||||
const user = userEvent.setup();
|
||||
let patchCalls = 0;
|
||||
server.use(
|
||||
http.patch('/api/auth/passkey/credentials/1', () => {
|
||||
patchCalls += 1;
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
serve({ credentials: [cred()] });
|
||||
render(<><ToastContainer /><PasskeysSection /></>);
|
||||
|
||||
await screen.findByText('MacBook');
|
||||
await user.click(within(item('MacBook')).getByRole('button', { name: 'Rename' }));
|
||||
await user.type(screen.getByDisplayValue('MacBook'), '{Escape}');
|
||||
await waitFor(() => expect(screen.queryByDisplayValue('MacBook')).not.toBeInTheDocument());
|
||||
expect(patchCalls).toBe(0);
|
||||
|
||||
await user.click(within(item('MacBook')).getByRole('button', { name: 'Rename' }));
|
||||
await user.type(screen.getByDisplayValue('MacBook'), '2{Enter}');
|
||||
await waitFor(() => expect(patchCalls).toBe(1));
|
||||
});
|
||||
|
||||
it('FE-COMP-PASSKEYS-018: clearing the name cancels the rename without calling the API', async () => {
|
||||
const user = userEvent.setup();
|
||||
let patchCalls = 0;
|
||||
server.use(http.patch('/api/auth/passkey/credentials/1', () => {
|
||||
patchCalls += 1;
|
||||
return HttpResponse.json({ success: true });
|
||||
}));
|
||||
serve({ credentials: [cred()] });
|
||||
render(<><ToastContainer /><PasskeysSection /></>);
|
||||
|
||||
await screen.findByText('MacBook');
|
||||
await user.click(within(item('MacBook')).getByRole('button', { name: 'Rename' }));
|
||||
await user.clear(screen.getByDisplayValue('MacBook'));
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
|
||||
await waitFor(() => expect(screen.getByText('MacBook')).toBeInTheDocument());
|
||||
expect(patchCalls).toBe(0);
|
||||
});
|
||||
|
||||
it('FE-COMP-PASSKEYS-022: the rename X button drops the edit and restores the row', async () => {
|
||||
const user = userEvent.setup();
|
||||
let patchCalls = 0;
|
||||
server.use(http.patch('/api/auth/passkey/credentials/1', () => {
|
||||
patchCalls += 1;
|
||||
return HttpResponse.json({ success: true });
|
||||
}));
|
||||
serve({ credentials: [cred()] });
|
||||
render(<><ToastContainer /><PasskeysSection /></>);
|
||||
|
||||
await screen.findByText('MacBook');
|
||||
await user.click(within(item('MacBook')).getByRole('button', { name: 'Rename' }));
|
||||
await user.type(screen.getByDisplayValue('MacBook'), '-edited');
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
|
||||
await waitFor(() => expect(screen.queryByRole('textbox')).not.toBeInTheDocument());
|
||||
expect(screen.getByText('MacBook')).toBeInTheDocument();
|
||||
expect(patchCalls).toBe(0);
|
||||
});
|
||||
|
||||
it('FE-COMP-PASSKEYS-019: a failing rename surfaces the server message', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(http.patch('/api/auth/passkey/credentials/1', () =>
|
||||
HttpResponse.json({ error: 'Name taken' }, { status: 409 })));
|
||||
serve({ credentials: [cred()] });
|
||||
render(<><ToastContainer /><PasskeysSection /></>);
|
||||
|
||||
await screen.findByText('MacBook');
|
||||
await user.click(within(item('MacBook')).getByRole('button', { name: 'Rename' }));
|
||||
await user.type(screen.getByDisplayValue('MacBook'), '-x');
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
|
||||
await screen.findByText('Name taken');
|
||||
});
|
||||
|
||||
it('FE-COMP-PASSKEYS-020: deleting asks for the password, calls the API and can be cancelled', async () => {
|
||||
const user = userEvent.setup();
|
||||
const sent: { body?: { password?: string } } = {};
|
||||
let listCalls = 0;
|
||||
server.use(
|
||||
http.get('/api/auth/passkey/credentials', () => {
|
||||
listCalls += 1;
|
||||
return HttpResponse.json({ credentials: listCalls === 1 ? [cred()] : [] });
|
||||
}),
|
||||
http.delete('/api/auth/passkey/credentials/1', async ({ request }) => {
|
||||
sent.body = await request.json() as { password?: string };
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
render(<><ToastContainer /><PasskeysSection /></>);
|
||||
|
||||
await screen.findByText('MacBook');
|
||||
await user.click(within(item('MacBook')).getByRole('button', { name: 'Delete' }));
|
||||
const panel = screen.getByText('Remove this passkey? Confirm with your password.').parentElement as HTMLElement;
|
||||
expect(within(panel).getByRole('button', { name: 'Delete' })).toBeDisabled();
|
||||
|
||||
await user.click(within(panel).getByRole('button', { name: 'Cancel' }));
|
||||
await waitFor(() => expect(screen.queryByText('Remove this passkey? Confirm with your password.')).not.toBeInTheDocument());
|
||||
|
||||
await user.click(within(item('MacBook')).getByRole('button', { name: 'Delete' }));
|
||||
const panel2 = screen.getByText('Remove this passkey? Confirm with your password.').parentElement as HTMLElement;
|
||||
await user.type(within(panel2).getByPlaceholderText('Current password'), 'hunter2');
|
||||
await user.click(within(panel2).getByRole('button', { name: 'Delete' }));
|
||||
|
||||
await screen.findByText('Passkey removed');
|
||||
expect(sent.body).toEqual({ password: 'hunter2' });
|
||||
await waitFor(() => expect(screen.queryByText('MacBook')).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('FE-COMP-PASSKEYS-021: a failing delete surfaces the server message and keeps the panel open', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(http.delete('/api/auth/passkey/credentials/1', () =>
|
||||
HttpResponse.json({ error: 'Wrong password' }, { status: 401 })));
|
||||
serve({ credentials: [cred()] });
|
||||
render(<><ToastContainer /><PasskeysSection /></>);
|
||||
|
||||
await screen.findByText('MacBook');
|
||||
await user.click(within(item('MacBook')).getByRole('button', { name: 'Delete' }));
|
||||
const panel = screen.getByText('Remove this passkey? Confirm with your password.').parentElement as HTMLElement;
|
||||
await user.type(within(panel).getByPlaceholderText('Current password'), 'nope');
|
||||
await user.click(within(panel).getByRole('button', { name: 'Delete' }));
|
||||
|
||||
await screen.findByText('Wrong password');
|
||||
expect(screen.getByText('Remove this passkey? Confirm with your password.')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-COMP-PHOTOPROVIDERS-001 to FE-COMP-PHOTOPROVIDERS-018
|
||||
// FE-COMP-PHOTOPROVIDERS-001 to FE-COMP-PHOTOPROVIDERS-024
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
@@ -15,12 +15,13 @@ const fakeProvider = {
|
||||
name: 'Immich',
|
||||
type: 'photo_provider',
|
||||
enabled: true,
|
||||
// Widened so per-test overrides can swap test_post for test_get.
|
||||
config: {
|
||||
settings_get: '/addons/immich/settings',
|
||||
settings_put: '/addons/immich/settings',
|
||||
status_get: '/addons/immich/status',
|
||||
test_post: '/addons/immich/test',
|
||||
},
|
||||
} as Record<string, string>,
|
||||
fields: [
|
||||
{ key: 'url', label: 'url', input_type: 'text', placeholder: 'https://...', required: true, secret: false, settings_key: 'url', payload_key: 'url', sort_order: 0 },
|
||||
{ key: 'api_key', label: 'api_key', input_type: 'text', placeholder: null, required: true, secret: true, settings_key: 'api_key', payload_key: 'api_key', sort_order: 1 },
|
||||
@@ -329,3 +330,141 @@ describe('PhotoProvidersSection', () => {
|
||||
await screen.findByText('Piwigo');
|
||||
});
|
||||
});
|
||||
|
||||
// ── Checkbox fields, missing values and failing probes (019–023) ──────────────
|
||||
|
||||
const providerWithCheckbox = {
|
||||
...fakeProvider,
|
||||
fields: [
|
||||
fakeProvider.fields[0],
|
||||
{
|
||||
key: 'verify_ssl',
|
||||
label: 'verify_ssl',
|
||||
input_type: 'checkbox',
|
||||
placeholder: null,
|
||||
required: false,
|
||||
secret: false,
|
||||
settings_key: 'verify_ssl',
|
||||
payload_key: 'verify_ssl',
|
||||
sort_order: 1,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
/** The ToggleSwitch rendered for a checkbox-typed provider field. */
|
||||
function checkboxToggle(): HTMLElement {
|
||||
return screen.getAllByRole('button').find(b => b.hasAttribute('aria-pressed')) as HTMLElement;
|
||||
}
|
||||
|
||||
describe('PhotoProvidersSection – checkbox fields and failures', () => {
|
||||
it('FE-COMP-PHOTOPROVIDERS-019: a checkbox field starts off and is sent as a boolean', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: Record<string, unknown> | null = null;
|
||||
server.use(
|
||||
http.put('/api/addons/immich/settings', async ({ request }) => {
|
||||
body = (await request.json()) as Record<string, unknown>;
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
seedMemoriesEnabled([providerWithCheckbox]);
|
||||
render(<PhotoProvidersSection />);
|
||||
|
||||
await screen.findByDisplayValue('https://photos.example.com');
|
||||
expect(checkboxToggle()).toHaveAttribute('aria-pressed', 'false');
|
||||
|
||||
await user.click(checkboxToggle());
|
||||
expect(checkboxToggle()).toHaveAttribute('aria-pressed', 'true');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /save/i }));
|
||||
|
||||
await waitFor(() => expect(body).toEqual({ url: 'https://photos.example.com', verify_ssl: true }));
|
||||
});
|
||||
|
||||
it('FE-COMP-PHOTOPROVIDERS-020: a stored checkbox value hydrates the toggle', async () => {
|
||||
server.use(
|
||||
http.get('/api/addons/immich/settings', () =>
|
||||
HttpResponse.json({ url: 'https://photos.example.com', verify_ssl: true, connected: false }),
|
||||
),
|
||||
);
|
||||
seedMemoriesEnabled([providerWithCheckbox]);
|
||||
render(<PhotoProvidersSection />);
|
||||
|
||||
await screen.findByDisplayValue('https://photos.example.com');
|
||||
await waitFor(() => expect(checkboxToggle()).toHaveAttribute('aria-pressed', 'true'));
|
||||
});
|
||||
|
||||
it('FE-COMP-PHOTOPROVIDERS-021: a settings payload without the field leaves the input empty', async () => {
|
||||
server.use(
|
||||
http.get('/api/addons/immich/settings', () => HttpResponse.json({ connected: false })),
|
||||
);
|
||||
seedMemoriesEnabled([fakeProviderSimple]);
|
||||
render(<PhotoProvidersSection />);
|
||||
|
||||
await screen.findByText('Immich');
|
||||
await waitFor(() => expect(screen.getByRole('textbox')).toHaveValue(''));
|
||||
expect(screen.getByRole('button', { name: /save/i })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-COMP-PHOTOPROVIDERS-022: a failing status probe leaves the provider disconnected', async () => {
|
||||
server.use(
|
||||
http.get('/api/addons/immich/settings', () => HttpResponse.json({ url: 'https://photos.example.com' })),
|
||||
http.get('/api/addons/immich/status', () => HttpResponse.json({ error: 'down' }, { status: 500 })),
|
||||
);
|
||||
seedMemoriesEnabled([fakeProviderSimple]);
|
||||
render(<PhotoProvidersSection />);
|
||||
|
||||
await screen.findByText('Immich');
|
||||
await waitFor(() => expect(screen.getByText('Not connected')).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('FE-COMP-PHOTOPROVIDERS-023: a test request that errors out falls back to the plain error', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.post('/api/addons/immich/test', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
|
||||
);
|
||||
seedMemoriesEnabled([fakeProviderSimple]);
|
||||
render(
|
||||
<>
|
||||
<ToastContainer />
|
||||
<PhotoProvidersSection />
|
||||
</>,
|
||||
);
|
||||
|
||||
await screen.findByText('Immich');
|
||||
await user.click(screen.getByRole('button', { name: /test connection/i }));
|
||||
|
||||
await screen.findByText('Could not connect to Immich');
|
||||
});
|
||||
|
||||
it('FE-COMP-PHOTOPROVIDERS-024: a provider without a test POST route probes over GET instead', async () => {
|
||||
const user = userEvent.setup();
|
||||
let probed = false;
|
||||
server.use(
|
||||
http.get('/api/addons/immich/probe', () => {
|
||||
probed = true;
|
||||
return HttpResponse.json({ connected: true });
|
||||
}),
|
||||
);
|
||||
seedMemoriesEnabled([{
|
||||
...fakeProviderSimple,
|
||||
config: {
|
||||
settings_get: '/addons/immich/settings',
|
||||
settings_put: '/addons/immich/settings',
|
||||
status_get: '/addons/immich/status',
|
||||
test_get: '/addons/immich/probe',
|
||||
},
|
||||
}]);
|
||||
render(
|
||||
<>
|
||||
<ToastContainer />
|
||||
<PhotoProvidersSection />
|
||||
</>,
|
||||
);
|
||||
|
||||
await screen.findByText('Immich');
|
||||
await user.click(screen.getByRole('button', { name: /test connection/i }));
|
||||
|
||||
await waitFor(() => expect(probed).toBe(true));
|
||||
await screen.findByText('Connected to Immich');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
// FE-COMP-PLUGINACTIVITY-001 to FE-COMP-PLUGINACTIVITY-010
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { render, screen, waitFor, within } from '../../../tests/helpers/render';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import PluginActivityPanel from './PluginActivityPanel';
|
||||
|
||||
interface ActivityRow {
|
||||
ts: string;
|
||||
plugin_id: string;
|
||||
plugin_name: string | null;
|
||||
method: string;
|
||||
resource: string | null;
|
||||
code: string;
|
||||
}
|
||||
|
||||
const row = (over: Partial<ActivityRow> = {}): ActivityRow => ({
|
||||
ts: '2025-06-01T10:00:00.000Z',
|
||||
plugin_id: 'weather',
|
||||
plugin_name: 'Weather',
|
||||
method: 'trips.read',
|
||||
resource: 'trip:42',
|
||||
code: 'ok',
|
||||
...over,
|
||||
});
|
||||
|
||||
function serveActivity(activity: ActivityRow[]): void {
|
||||
server.use(http.get('/api/plugin-activity', () => HttpResponse.json({ activity })));
|
||||
}
|
||||
|
||||
/** The <td> cells of the one rendered data row. */
|
||||
const cells = () => within(screen.getByRole('table')).getAllByRole('row')[1].querySelectorAll('td');
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
serveActivity([]);
|
||||
});
|
||||
|
||||
describe('PluginActivityPanel', () => {
|
||||
it('FE-COMP-PLUGINACTIVITY-001: shows the loading line before the log arrives', async () => {
|
||||
server.use(http.get('/api/plugin-activity', () => new Promise(() => {})));
|
||||
render(<PluginActivityPanel />);
|
||||
|
||||
expect(screen.getByText('Plugin activity')).toBeInTheDocument();
|
||||
expect(screen.getByText('Loading...')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Refresh' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINACTIVITY-002: an empty log renders the empty state instead of a table', async () => {
|
||||
render(<PluginActivityPanel />);
|
||||
|
||||
expect(await screen.findByText('No plugin activity yet.')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('table')).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Refresh' })).toBeEnabled();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINACTIVITY-003: a failing request falls back to the empty state, not a crash', async () => {
|
||||
server.use(http.get('/api/plugin-activity', () => HttpResponse.json({ error: 'nope' }, { status: 500 })));
|
||||
render(<PluginActivityPanel />);
|
||||
|
||||
expect(await screen.findByText('No plugin activity yet.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINACTIVITY-004: entries render as a table with all five columns', async () => {
|
||||
serveActivity([row()]);
|
||||
render(<PluginActivityPanel />);
|
||||
|
||||
const table = await screen.findByRole('table');
|
||||
const headers = within(table).getAllByRole('columnheader').map(th => th.textContent);
|
||||
expect(headers).toEqual(['Plugin', 'Action', 'Resource', 'When', 'Result']);
|
||||
expect(within(table).getByText('Weather')).toBeInTheDocument();
|
||||
expect(within(table).getByText('trips.read')).toBeInTheDocument();
|
||||
expect(within(table).getByText('trip:42')).toBeInTheDocument();
|
||||
expect(within(table).getByText('ok')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINACTIVITY-005: a nameless plugin falls back to its id and a null resource to a dash', async () => {
|
||||
serveActivity([row({ plugin_name: null, resource: null })]);
|
||||
render(<PluginActivityPanel />);
|
||||
|
||||
await screen.findByRole('table');
|
||||
expect(cells()[0]).toHaveTextContent('weather');
|
||||
expect(cells()[2]).toHaveTextContent('—');
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINACTIVITY-006: an "ok" code gets the neutral pill', async () => {
|
||||
serveActivity([row({ code: 'ok' })]);
|
||||
render(<PluginActivityPanel />);
|
||||
|
||||
await screen.findByRole('table');
|
||||
expect(screen.getByText('ok')).toHaveClass('bg-surface-hover', 'text-content-secondary');
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINACTIVITY-007: an access denial gets the danger pill', async () => {
|
||||
serveActivity([row({ code: 'FORBIDDEN' })]);
|
||||
render(<PluginActivityPanel />);
|
||||
|
||||
await screen.findByRole('table');
|
||||
expect(screen.getByText('FORBIDDEN')).toHaveClass('bg-danger-soft', 'text-danger');
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINACTIVITY-008: any other non-ok code gets the warning pill', async () => {
|
||||
serveActivity([row({ code: 'RATE_LIMITED' })]);
|
||||
render(<PluginActivityPanel />);
|
||||
|
||||
await screen.findByRole('table');
|
||||
expect(screen.getByText('RATE_LIMITED')).toHaveClass('bg-warning-soft', 'text-warning');
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINACTIVITY-009: an unparseable timestamp is shown verbatim', async () => {
|
||||
serveActivity([row({ ts: 'not-a-date' })]);
|
||||
render(<PluginActivityPanel />);
|
||||
|
||||
await screen.findByRole('table');
|
||||
expect(cells()[3]).toHaveTextContent('not-a-date');
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINACTIVITY-010: Refresh re-reads the log', async () => {
|
||||
const user = userEvent.setup();
|
||||
let calls = 0;
|
||||
server.use(http.get('/api/plugin-activity', () => {
|
||||
calls += 1;
|
||||
return HttpResponse.json({ activity: calls === 1 ? [] : [row({ plugin_name: 'Second pass' })] });
|
||||
}));
|
||||
render(<PluginActivityPanel />);
|
||||
|
||||
await screen.findByText('No plugin activity yet.');
|
||||
await user.click(screen.getByRole('button', { name: 'Refresh' }));
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Second pass')).toBeInTheDocument());
|
||||
expect(calls).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,451 @@
|
||||
// FE-COMP-PLUGINSETTINGS-001 to FE-COMP-PLUGINSETTINGS-025
|
||||
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, within } from '../../../tests/helpers/render';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { ToastContainer } from '../shared/Toast';
|
||||
import { usePluginStore, type ActivePlugin } from '../../store/pluginStore';
|
||||
import type { PluginAction, PluginUserSettingField } from '../../api/client';
|
||||
import PluginSettingsTab from './PluginSettingsTab';
|
||||
|
||||
const plugin = (over: Partial<ActivePlugin> = {}): ActivePlugin => ({
|
||||
id: 'weather',
|
||||
name: 'Weather',
|
||||
type: 'widget',
|
||||
icon: 'Cloud',
|
||||
...over,
|
||||
});
|
||||
|
||||
interface SettingsPayload {
|
||||
fields?: PluginUserSettingField[]
|
||||
config?: Record<string, unknown>
|
||||
actions?: PluginAction[]
|
||||
}
|
||||
|
||||
/** Wire the three per-plugin endpoints the form reads on mount. */
|
||||
function serve(id: string, settings: SettingsPayload, oauth?: { configured: boolean; connected: boolean }): void {
|
||||
server.use(
|
||||
http.get(`/api/plugin-settings/${id}`, () => HttpResponse.json({
|
||||
fields: settings.fields ?? [],
|
||||
config: settings.config ?? {},
|
||||
actions: settings.actions ?? [],
|
||||
})),
|
||||
http.get(`/api/plugin-oauth/${id}/status`, () =>
|
||||
oauth ? HttpResponse.json(oauth) : HttpResponse.json({ error: 'not found' }, { status: 404 })),
|
||||
);
|
||||
}
|
||||
|
||||
function setPlugins(plugins: ActivePlugin[]): void {
|
||||
usePluginStore.setState({ plugins });
|
||||
}
|
||||
|
||||
/** The settings card for a plugin (the heading's rounded container). */
|
||||
const cardFor = (name: string) => screen.getByRole('heading', { name }).closest('div.rounded-xl') as HTMLElement;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
setPlugins([]);
|
||||
server.use(http.get('/api/plugin-activity', () => HttpResponse.json({ activity: [] })));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('PluginSettingsTab', () => {
|
||||
it('FE-COMP-PLUGINSETTINGS-001: shows the header and the empty state when no plugin is active', async () => {
|
||||
render(<PluginSettingsTab />);
|
||||
|
||||
expect(screen.getByRole('heading', { name: 'Plugin settings' })).toBeInTheDocument();
|
||||
expect(screen.getByText('Your personal settings for the plugins you use (API keys, preferences).')).toBeInTheDocument();
|
||||
expect(screen.getByText('No plugins are active.')).toBeInTheDocument();
|
||||
// The activity log is always mounted, plugins or not.
|
||||
expect(await screen.findByText('Plugin activity')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-002: a plugin with nothing to configure renders no card', async () => {
|
||||
serve('weather', {});
|
||||
setPlugins([plugin()]);
|
||||
render(<PluginSettingsTab />);
|
||||
|
||||
await screen.findByText('Plugin activity');
|
||||
expect(screen.queryByText('No plugins are active.')).not.toBeInTheDocument();
|
||||
await waitFor(() => expect(screen.queryByRole('heading', { name: 'Weather' })).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-003: a failing settings request leaves the card out', async () => {
|
||||
server.use(
|
||||
http.get('/api/plugin-settings/weather', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
|
||||
http.get('/api/plugin-oauth/weather/status', () => HttpResponse.json({ configured: false, connected: false })),
|
||||
);
|
||||
setPlugins([plugin()]);
|
||||
render(<PluginSettingsTab />);
|
||||
|
||||
await screen.findByText('Plugin activity');
|
||||
await waitFor(() => expect(screen.queryByRole('heading', { name: 'Weather' })).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-004: text fields are labelled, prefilled and marked required', async () => {
|
||||
serve('weather', {
|
||||
fields: [
|
||||
{ key: 'api_key', label: 'API key', input_type: 'text', required: true, hint: 'From your provider' },
|
||||
{ key: 'units', input_type: 'text' },
|
||||
],
|
||||
config: { api_key: 'abc123', units: 'metric' },
|
||||
});
|
||||
setPlugins([plugin()]);
|
||||
render(<PluginSettingsTab />);
|
||||
|
||||
await screen.findByDisplayValue('abc123');
|
||||
const card = cardFor('Weather');
|
||||
expect(within(card).getByText('API key')).toHaveTextContent('*');
|
||||
expect(within(card).getByText('From your provider')).toBeInTheDocument();
|
||||
// No label declared → the key stands in for it.
|
||||
expect(within(card).getByText('units')).toBeInTheDocument();
|
||||
expect(within(card).getByDisplayValue('metric')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-005: a secret field renders as a password input with a placeholder', async () => {
|
||||
serve('weather', {
|
||||
fields: [{ key: 'token', label: 'Token', input_type: 'text', secret: true, placeholder: 'paste here' }],
|
||||
config: { token: '••••••••' },
|
||||
});
|
||||
setPlugins([plugin()]);
|
||||
render(<PluginSettingsTab />);
|
||||
|
||||
const input = await screen.findByPlaceholderText('paste here') as HTMLInputElement;
|
||||
expect(input.type).toBe('password');
|
||||
expect(input.autocomplete).toBe('new-password');
|
||||
expect(input.value).toBe('••••••••');
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-006: a number field renders a numeric input and a null config value is blank', async () => {
|
||||
serve('weather', {
|
||||
fields: [{ key: 'days', label: 'Days', input_type: 'number' }],
|
||||
config: { days: null },
|
||||
});
|
||||
setPlugins([plugin()]);
|
||||
render(<PluginSettingsTab />);
|
||||
|
||||
const input = await screen.findByRole('spinbutton') as HTMLInputElement;
|
||||
expect(input.type).toBe('number');
|
||||
expect(input.value).toBe('');
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-007: a checkbox field mirrors the boolean config and toggles', async () => {
|
||||
const user = userEvent.setup();
|
||||
serve('weather', {
|
||||
fields: [{ key: 'alerts', label: 'Alerts', input_type: 'checkbox' }],
|
||||
config: { alerts: true },
|
||||
});
|
||||
setPlugins([plugin()]);
|
||||
render(<PluginSettingsTab />);
|
||||
|
||||
const box = await screen.findByRole('checkbox');
|
||||
expect(box).toBeChecked();
|
||||
await user.click(box);
|
||||
expect(box).not.toBeChecked();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-008: a select field lists its options and keeps the chosen one', async () => {
|
||||
const user = userEvent.setup();
|
||||
serve('weather', {
|
||||
fields: [{
|
||||
key: 'unit', label: 'Unit', input_type: 'select',
|
||||
options: [{ value: 'c', label: 'Celsius' }, { value: 'f', label: 'Fahrenheit' }],
|
||||
}],
|
||||
config: { unit: 'c' },
|
||||
});
|
||||
setPlugins([plugin()]);
|
||||
render(<PluginSettingsTab />);
|
||||
|
||||
const select = await screen.findByRole('combobox') as HTMLSelectElement;
|
||||
expect(select.value).toBe('c');
|
||||
await user.selectOptions(select, 'f');
|
||||
expect(select.value).toBe('f');
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-009: a select field without options falls back to a text input', async () => {
|
||||
serve('weather', {
|
||||
fields: [{ key: 'unit', label: 'Unit', input_type: 'select' }],
|
||||
config: { unit: 'c' },
|
||||
});
|
||||
setPlugins([plugin()]);
|
||||
render(<PluginSettingsTab />);
|
||||
|
||||
expect(await screen.findByDisplayValue('c')).toHaveAttribute('type', 'text');
|
||||
expect(screen.queryByRole('combobox')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-010: saving posts the edited values and echoes back the stored config', async () => {
|
||||
const user = userEvent.setup();
|
||||
const sent: { body?: { config?: Record<string, unknown> } } = {};
|
||||
serve('weather', {
|
||||
fields: [
|
||||
{ key: 'api_key', label: 'API key', input_type: 'text' },
|
||||
{ key: 'alerts', label: 'Alerts', input_type: 'checkbox' },
|
||||
],
|
||||
config: { api_key: 'old', alerts: false },
|
||||
});
|
||||
server.use(http.post('/api/plugin-settings/weather', async ({ request }) => {
|
||||
sent.body = await request.json() as { config?: Record<string, unknown> };
|
||||
return HttpResponse.json({ config: { api_key: 'new-key', alerts: true } });
|
||||
}));
|
||||
setPlugins([plugin()]);
|
||||
render(<><ToastContainer /><PluginSettingsTab /></>);
|
||||
|
||||
const input = await screen.findByDisplayValue('old');
|
||||
await user.clear(input);
|
||||
await user.type(input, 'new-key');
|
||||
await user.click(screen.getByRole('checkbox'));
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
|
||||
await screen.findByText('Settings saved');
|
||||
expect(sent.body?.config).toEqual({ api_key: 'new-key', alerts: true });
|
||||
expect(await screen.findByDisplayValue('new-key')).toBeInTheDocument();
|
||||
expect(screen.getByRole('checkbox')).toBeChecked();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-011: an untouched secret is not overwritten with its mask', async () => {
|
||||
const user = userEvent.setup();
|
||||
const sent: { body?: { config?: Record<string, unknown> } } = {};
|
||||
serve('weather', {
|
||||
fields: [
|
||||
{ key: 'token', label: 'Token', input_type: 'text', secret: true },
|
||||
{ key: 'city', label: 'City', input_type: 'text' },
|
||||
],
|
||||
config: { token: '••••••••', city: 'Berlin' },
|
||||
});
|
||||
server.use(http.post('/api/plugin-settings/weather', async ({ request }) => {
|
||||
sent.body = await request.json() as { config?: Record<string, unknown> };
|
||||
return HttpResponse.json({ config: { token: '••••••••', city: 'Paris' } });
|
||||
}));
|
||||
setPlugins([plugin()]);
|
||||
render(<><ToastContainer /><PluginSettingsTab /></>);
|
||||
|
||||
const city = await screen.findByDisplayValue('Berlin');
|
||||
await user.clear(city);
|
||||
await user.type(city, 'Paris');
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
|
||||
await screen.findByText('Settings saved');
|
||||
expect(sent.body?.config).toEqual({ city: 'Paris' });
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-012: a changed secret IS sent', async () => {
|
||||
const user = userEvent.setup();
|
||||
const sent: { body?: { config?: Record<string, unknown> } } = {};
|
||||
serve('weather', {
|
||||
fields: [{ key: 'token', label: 'Token', input_type: 'text', secret: true }],
|
||||
config: { token: '••••••••' },
|
||||
});
|
||||
server.use(http.post('/api/plugin-settings/weather', async ({ request }) => {
|
||||
sent.body = await request.json() as { config?: Record<string, unknown> };
|
||||
return HttpResponse.json({ config: { token: '••••••••' } });
|
||||
}));
|
||||
setPlugins([plugin()]);
|
||||
render(<><ToastContainer /><PluginSettingsTab /></>);
|
||||
|
||||
const token = await screen.findByDisplayValue('••••••••');
|
||||
await user.clear(token);
|
||||
await user.type(token, 'real-secret');
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
|
||||
await screen.findByText('Settings saved');
|
||||
expect(sent.body?.config).toEqual({ token: 'real-secret' });
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-013: a failing save reports an error and re-enables the button', async () => {
|
||||
const user = userEvent.setup();
|
||||
serve('weather', {
|
||||
fields: [{ key: 'city', label: 'City', input_type: 'text' }],
|
||||
config: { city: 'Berlin' },
|
||||
});
|
||||
server.use(http.post('/api/plugin-settings/weather', () =>
|
||||
HttpResponse.json({ error: 'nope' }, { status: 500 })));
|
||||
setPlugins([plugin()]);
|
||||
render(<><ToastContainer /><PluginSettingsTab /></>);
|
||||
|
||||
await screen.findByDisplayValue('Berlin');
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
|
||||
await screen.findByText('Error');
|
||||
expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-014: a plugin with only actions gets a card without a Save button', async () => {
|
||||
serve('weather', { actions: [{ key: 'test', label: 'Test connection', hint: 'Pings the API', danger: false }] });
|
||||
setPlugins([plugin()]);
|
||||
render(<PluginSettingsTab />);
|
||||
|
||||
await screen.findByRole('button', { name: 'Test connection' });
|
||||
const card = cardFor('Weather');
|
||||
expect(within(card).getByText('Actions')).toBeInTheDocument();
|
||||
expect(within(card).getByText('Pings the API')).toBeInTheDocument();
|
||||
expect(within(card).queryByRole('button', { name: 'Save' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-015: running an action shows the message it returns', async () => {
|
||||
const user = userEvent.setup();
|
||||
serve('weather', { actions: [{ key: 'test', label: 'Test connection', danger: false }] });
|
||||
server.use(http.post('/api/plugin-settings/weather/actions/test', () =>
|
||||
HttpResponse.json({ ok: true, message: 'Reached the API' })));
|
||||
setPlugins([plugin()]);
|
||||
render(<PluginSettingsTab />);
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Test connection' }));
|
||||
expect(await screen.findByText('Reached the API')).toHaveClass('text-success');
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-016: a message-less result falls back to the generic ok/error labels', async () => {
|
||||
const user = userEvent.setup();
|
||||
serve('weather', { actions: [{ key: 'test', label: 'Test connection', danger: false }] });
|
||||
server.use(http.post('/api/plugin-settings/weather/actions/test', () => HttpResponse.json({ ok: false })));
|
||||
setPlugins([plugin()]);
|
||||
render(<PluginSettingsTab />);
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Test connection' }));
|
||||
expect(await screen.findByText('Error')).toHaveClass('text-danger');
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-017: a failing action reports an error result', async () => {
|
||||
const user = userEvent.setup();
|
||||
serve('weather', { actions: [{ key: 'test', label: 'Test connection', danger: false }] });
|
||||
server.use(http.post('/api/plugin-settings/weather/actions/test', () =>
|
||||
HttpResponse.json({ error: 'down' }, { status: 500 })));
|
||||
setPlugins([plugin()]);
|
||||
render(<PluginSettingsTab />);
|
||||
|
||||
const button = await screen.findByRole('button', { name: 'Test connection' });
|
||||
await user.click(button);
|
||||
expect(await screen.findByText('Error')).toHaveClass('text-danger');
|
||||
expect(button).toBeEnabled();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-018: a dangerous action asks first and a declined confirm skips it', async () => {
|
||||
const user = userEvent.setup();
|
||||
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);
|
||||
let ran = 0;
|
||||
serve('weather', { actions: [{ key: 'wipe', label: 'Wipe cache', danger: true }] });
|
||||
server.use(http.post('/api/plugin-settings/weather/actions/wipe', () => {
|
||||
ran += 1;
|
||||
return HttpResponse.json({ ok: true, message: 'Wiped' });
|
||||
}));
|
||||
setPlugins([plugin()]);
|
||||
render(<PluginSettingsTab />);
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Wipe cache' }));
|
||||
expect(confirmSpy).toHaveBeenCalledWith('Run this action?');
|
||||
expect(ran).toBe(0);
|
||||
|
||||
confirmSpy.mockReturnValue(true);
|
||||
await user.click(screen.getByRole('button', { name: 'Wipe cache' }));
|
||||
await screen.findByText('Wiped');
|
||||
expect(ran).toBe(1);
|
||||
confirmSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-019: an unconfigured OAuth integration renders no connect row', async () => {
|
||||
serve('weather', {
|
||||
fields: [{ key: 'city', label: 'City', input_type: 'text' }],
|
||||
config: { city: 'Berlin' },
|
||||
}, { configured: false, connected: false });
|
||||
setPlugins([plugin()]);
|
||||
render(<PluginSettingsTab />);
|
||||
|
||||
await screen.findByDisplayValue('Berlin');
|
||||
expect(screen.queryByRole('button', { name: 'Connect' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Not connected')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-020: an OAuth-only plugin gets a card and Connect hands off to the provider', async () => {
|
||||
const user = userEvent.setup();
|
||||
const loc = { href: 'http://localhost/settings', origin: 'http://localhost', pathname: '/settings' };
|
||||
vi.stubGlobal('location', loc);
|
||||
serve('weather', {}, { configured: true, connected: false });
|
||||
server.use(http.post('/api/plugin-oauth/weather/connect', () =>
|
||||
HttpResponse.json({ authorizeUrl: 'https://provider.example/authorize?x=1' })));
|
||||
setPlugins([plugin()]);
|
||||
render(<PluginSettingsTab />);
|
||||
|
||||
expect(await screen.findByText('Not connected')).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Connect' }));
|
||||
|
||||
await waitFor(() => expect(loc.href).toBe('https://provider.example/authorize?x=1'));
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-021: a failing connect reports an error and frees the button', async () => {
|
||||
const user = userEvent.setup();
|
||||
serve('weather', {}, { configured: true, connected: false });
|
||||
server.use(http.post('/api/plugin-oauth/weather/connect', () =>
|
||||
HttpResponse.json({ error: 'nope' }, { status: 500 })));
|
||||
setPlugins([plugin()]);
|
||||
render(<><ToastContainer /><PluginSettingsTab /></>);
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Connect' }));
|
||||
|
||||
await screen.findByText('Error');
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Connect' })).toBeEnabled());
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-022: disconnecting flips the row back to "not connected"', async () => {
|
||||
const user = userEvent.setup();
|
||||
serve('weather', {}, { configured: true, connected: true });
|
||||
server.use(http.post('/api/plugin-oauth/weather/disconnect', () => HttpResponse.json({ connected: false })));
|
||||
setPlugins([plugin()]);
|
||||
render(<PluginSettingsTab />);
|
||||
|
||||
expect(await screen.findByText('Connected')).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Disconnect' }));
|
||||
|
||||
expect(await screen.findByText('Not connected')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Connect' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-023: a failing disconnect keeps the connection and reports an error', async () => {
|
||||
const user = userEvent.setup();
|
||||
serve('weather', {}, { configured: true, connected: true });
|
||||
server.use(http.post('/api/plugin-oauth/weather/disconnect', () =>
|
||||
HttpResponse.json({ error: 'nope' }, { status: 500 })));
|
||||
setPlugins([plugin()]);
|
||||
render(<><ToastContainer /><PluginSettingsTab /></>);
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Disconnect' }));
|
||||
|
||||
await screen.findByText('Error');
|
||||
expect(screen.getByRole('button', { name: 'Disconnect' })).toBeEnabled();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-024: a settingsUi plugin also gets its own sandboxed frame card', async () => {
|
||||
serve('weather', {
|
||||
fields: [{ key: 'city', label: 'City', input_type: 'text' }],
|
||||
config: { city: 'Berlin' },
|
||||
});
|
||||
setPlugins([plugin({ settingsUi: true })]);
|
||||
const { container } = render(<PluginSettingsTab />);
|
||||
|
||||
await screen.findByDisplayValue('Berlin');
|
||||
expect(screen.getAllByRole('heading', { name: 'Weather' })).toHaveLength(2);
|
||||
const frame = container.querySelector('iframe') as HTMLIFrameElement;
|
||||
expect(frame).not.toBeNull();
|
||||
expect(frame.getAttribute('src')).toBe('/plugin-frame/weather/settings.html');
|
||||
expect(frame.getAttribute('sandbox') || '').not.toContain('allow-same-origin');
|
||||
});
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-025: every active plugin gets its own form', async () => {
|
||||
serve('weather', { fields: [{ key: 'city', label: 'City', input_type: 'text' }], config: { city: 'Berlin' } });
|
||||
server.use(
|
||||
http.get('/api/plugin-settings/notes', () => HttpResponse.json({
|
||||
fields: [{ key: 'folder', label: 'Folder', input_type: 'text' }], config: { folder: 'Trips' }, actions: [],
|
||||
})),
|
||||
http.get('/api/plugin-oauth/notes/status', () => HttpResponse.json({ configured: false, connected: false })),
|
||||
);
|
||||
setPlugins([plugin(), plugin({ id: 'notes', name: 'Notes', icon: null })]);
|
||||
render(<PluginSettingsTab />);
|
||||
|
||||
await screen.findByDisplayValue('Berlin');
|
||||
expect(await screen.findByDisplayValue('Trips')).toBeInTheDocument();
|
||||
expect(within(cardFor('Notes')).getByText('Folder')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,159 @@
|
||||
// FE-COMP-NAVEDITOR-001 to FE-COMP-NAVEDITOR-014
|
||||
import React from 'react';
|
||||
import { renderHook } from '../../../tests/helpers/render';
|
||||
import { act } from '@testing-library/react';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { useAddonStore } from '../../store/addonStore';
|
||||
import { usePluginStore } from '../../store/pluginStore';
|
||||
import { TranslationProvider } from '../../i18n/TranslationContext';
|
||||
import { useMobileNavEditor, type MobileNavValue } from './useMobileNavEditor';
|
||||
|
||||
const GLOBAL_ADDONS = [
|
||||
{ id: 'vacay', name: 'Vacay', type: 'global', icon: 'calendar', enabled: true },
|
||||
{ id: 'atlas', name: 'Atlas', type: 'global', icon: 'map', enabled: true },
|
||||
{ id: 'journey', name: 'Journey', type: 'global', icon: 'compass', enabled: true },
|
||||
{ id: 'collections', name: 'Collections', type: 'global', icon: 'bookmark', enabled: true },
|
||||
];
|
||||
|
||||
function wrapper({ children }: { children: React.ReactNode }) {
|
||||
return <TranslationProvider>{children}</TranslationProvider>;
|
||||
}
|
||||
|
||||
function setup(value: MobileNavValue) {
|
||||
const onChange = vi.fn<(next: MobileNavValue) => void>();
|
||||
const { result } = renderHook(() => useMobileNavEditor(value, onChange), { wrapper });
|
||||
return { result, onChange };
|
||||
}
|
||||
|
||||
const ids = (items: { id: string }[]) => items.map(i => i.id);
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
vi.clearAllMocks();
|
||||
seedStore(useAddonStore, { addons: GLOBAL_ADDONS, loaded: true });
|
||||
usePluginStore.setState({ plugins: [], loaded: true });
|
||||
});
|
||||
|
||||
describe('useMobileNavEditor', () => {
|
||||
it('FE-COMP-NAVEDITOR-001: an empty value falls back to the built-in dock split', () => {
|
||||
const { result } = setup({ bar: [], more: [] });
|
||||
|
||||
expect(ids(result.current.barItems)).toEqual(['vacay', 'atlas']);
|
||||
expect(ids(result.current.moreItems)).toEqual(['journey', 'collections']);
|
||||
expect(result.current.hasMore).toBe(true);
|
||||
expect(result.current.barFull).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-COMP-NAVEDITOR-002: Dashboard is pinned, kept out of barItems and first in the preview', () => {
|
||||
const { result } = setup({ bar: ['vacay'], more: ['atlas'] });
|
||||
|
||||
expect(result.current.dashboard?.id).toBe('dashboard');
|
||||
expect(ids(result.current.barItems)).toEqual(['vacay']);
|
||||
expect(ids(result.current.previewBar)).toEqual(['dashboard', 'vacay']);
|
||||
});
|
||||
|
||||
it('FE-COMP-NAVEDITOR-003: a bar that is not full reports barFull false', () => {
|
||||
const { result } = setup({ bar: ['vacay'], more: ['atlas', 'journey', 'collections'] });
|
||||
|
||||
expect(result.current.barFull).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-COMP-NAVEDITOR-004: everything in the bar leaves More empty', () => {
|
||||
seedStore(useAddonStore, { addons: GLOBAL_ADDONS.slice(0, 2), loaded: true });
|
||||
const { result } = setup({ bar: ['vacay', 'atlas'], more: [] });
|
||||
|
||||
expect(result.current.moreItems).toEqual([]);
|
||||
expect(result.current.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-COMP-NAVEDITOR-005: moving a bar item up emits the reordered id list', () => {
|
||||
const { result, onChange } = setup({ bar: ['vacay', 'atlas'], more: ['journey', 'collections'] });
|
||||
|
||||
act(() => result.current.move('bar', 1, 0));
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({ bar: ['atlas', 'vacay'], more: ['journey', 'collections'] });
|
||||
});
|
||||
|
||||
it('FE-COMP-NAVEDITOR-006: moving inside More leaves the bar untouched', () => {
|
||||
const { result, onChange } = setup({ bar: ['vacay'], more: ['journey', 'atlas', 'collections'] });
|
||||
|
||||
act(() => result.current.move('more', 0, 1));
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({ bar: ['vacay'], more: ['atlas', 'journey', 'collections'] });
|
||||
});
|
||||
|
||||
it('FE-COMP-NAVEDITOR-007: a move past the end of a zone emits the list unchanged', () => {
|
||||
const { result, onChange } = setup({ bar: ['vacay', 'atlas'], more: ['journey', 'collections'] });
|
||||
|
||||
act(() => result.current.move('bar', 1, 2));
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({ bar: ['vacay', 'atlas'], more: ['journey', 'collections'] });
|
||||
});
|
||||
|
||||
it('FE-COMP-NAVEDITOR-008: a move before the start of a zone emits the list unchanged', () => {
|
||||
const { result, onChange } = setup({ bar: ['vacay', 'atlas'], more: ['journey', 'collections'] });
|
||||
|
||||
act(() => result.current.move('bar', 0, -1));
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({ bar: ['vacay', 'atlas'], more: ['journey', 'collections'] });
|
||||
});
|
||||
|
||||
it('FE-COMP-NAVEDITOR-009: a move onto itself emits the list unchanged', () => {
|
||||
const { result, onChange } = setup({ bar: ['vacay', 'atlas'], more: ['journey', 'collections'] });
|
||||
|
||||
act(() => result.current.move('bar', 1, 1));
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({ bar: ['vacay', 'atlas'], more: ['journey', 'collections'] });
|
||||
});
|
||||
|
||||
it('FE-COMP-NAVEDITOR-010: demoting a bar item appends it to the end of More', () => {
|
||||
const { result, onChange } = setup({ bar: ['vacay', 'atlas'], more: ['journey', 'collections'] });
|
||||
|
||||
act(() => result.current.toMore('vacay'));
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({ bar: ['atlas'], more: ['journey', 'collections', 'vacay'] });
|
||||
});
|
||||
|
||||
it('FE-COMP-NAVEDITOR-011: demoting an id that is not in the bar is a no-op', () => {
|
||||
const { result, onChange } = setup({ bar: ['vacay', 'atlas'], more: ['journey', 'collections'] });
|
||||
|
||||
act(() => result.current.toMore('journey'));
|
||||
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-NAVEDITOR-012: promoting appends to the bar and drops the item from More', () => {
|
||||
const { result, onChange } = setup({ bar: ['vacay'], more: ['journey', 'atlas', 'collections'] });
|
||||
|
||||
act(() => result.current.toBar('atlas'));
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({ bar: ['vacay', 'atlas'], more: ['journey', 'collections'] });
|
||||
});
|
||||
|
||||
it('FE-COMP-NAVEDITOR-013: promoting is refused when the bar is full or the id is unknown', () => {
|
||||
const full = setup({ bar: ['vacay', 'atlas'], more: ['journey', 'collections'] });
|
||||
act(() => full.result.current.toBar('journey'));
|
||||
expect(full.onChange).not.toHaveBeenCalled();
|
||||
|
||||
const room = setup({ bar: ['vacay'], more: ['journey', 'atlas', 'collections'] });
|
||||
act(() => room.result.current.toBar('does-not-exist'));
|
||||
expect(room.onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-NAVEDITOR-014: page plugins take part in the split under their plugin id', () => {
|
||||
usePluginStore.setState({
|
||||
plugins: [{ id: 'todos', name: 'Trip To-Dos', type: 'page', icon: 'list' }] as never,
|
||||
loaded: true,
|
||||
});
|
||||
const { result, onChange } = setup({ bar: ['vacay'], more: ['plugin:todos'] });
|
||||
|
||||
// Items the stored config never mentioned are appended under More.
|
||||
expect(ids(result.current.moreItems)).toEqual(['plugin:todos', 'atlas', 'journey', 'collections']);
|
||||
|
||||
act(() => result.current.toBar('plugin:todos'));
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
bar: ['vacay', 'plugin:todos'],
|
||||
more: ['atlas', 'journey', 'collections'],
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user