test(client): the coverage that goes with the previous commits

Left out of the commits they belong to by hand, not by intent: the mobile
screen suites, the tripRepo cache-first read behind the startup-destination
fix, and the MSW handlers the stricter unhandled-request setting needs.
This commit is contained in:
Maurice
2026-08-23 10:09:05 +02:00
committed by Maurice
parent c75e958fc0
commit 27be764164
25 changed files with 749 additions and 23 deletions
+48 -1
View File
@@ -1,4 +1,4 @@
// FE-REPO-TRIP-001 to FE-REPO-TRIP-007
// FE-REPO-TRIP-001 to FE-REPO-TRIP-011
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import 'fake-indexeddb/auto'
import { http, HttpResponse } from 'msw'
@@ -97,3 +97,50 @@ describe('tripRepo.get', () => {
expect(result.trip.title).toBe('Fallback')
})
})
describe('tripRepo.active', () => {
// Local calendar dates, like the repo itself.
function dateOffset(days: number): string {
const d = new Date()
d.setDate(d.getDate() + days)
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}
it('FE-REPO-TRIP-008: online — passes the server answer straight through', async () => {
server.use(http.get('/api/trips/active', () =>
HttpResponse.json({ trip: { id: 90, title: 'Server pick', start_date: null, end_date: null } }),
))
const result = await tripRepo.active()
expect(result.trip!.id).toBe(90)
})
it('FE-REPO-TRIP-009: offline — ranks ongoing over upcoming over past', async () => {
await offlineDb.trips.put(buildTrip({ id: 91, start_date: dateOffset(-40), end_date: dateOffset(-30) }))
await offlineDb.trips.put(buildTrip({ id: 92, start_date: dateOffset(10), end_date: dateOffset(14) }))
await offlineDb.trips.put(buildTrip({ id: 93, start_date: dateOffset(-1), end_date: dateOffset(2) }))
setOnline(false)
expect((await tripRepo.active()).trip!.id).toBe(93)
await offlineDb.trips.delete(93)
expect((await tripRepo.active()).trip!.id).toBe(92)
await offlineDb.trips.delete(92)
expect((await tripRepo.active()).trip!.id).toBe(91)
})
it('FE-REPO-TRIP-010: offline — skips archived trips and answers null when nothing is left', async () => {
await offlineDb.trips.put(buildTrip({ id: 94, is_archived: 1, start_date: dateOffset(-1), end_date: dateOffset(2) }))
setOnline(false)
expect((await tripRepo.active()).trip).toBeNull()
})
it('FE-REPO-TRIP-011: an HTTP error still rejects instead of falling back', async () => {
await offlineDb.trips.put(buildTrip({ id: 95 }))
server.use(http.get('/api/trips/active', () => HttpResponse.json({ error: 'boom' }, { status: 500 })))
await expect(tripRepo.active()).rejects.toThrow()
})
})
+46
View File
@@ -2,6 +2,32 @@ import { tripsApi } from '../api/client'
import { offlineDb, upsertTrip } from '../db/offlineDb'
import { onlineThenCache } from './withOfflineFallback'
import type { Trip } from '../types'
import type { ActiveTripResponse } from '@trek/shared'
/**
* Offline stand-in for GET /trips/active. Mirrors the server's ranking
* (trips.service.ts activeTrip): the trip running today, else the next one to
* start, else the most recently started. Dates are plain local calendar dates.
*/
function pickActive(trips: Trip[]): Trip | null {
const now = new Date()
const today = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
const relevance = (t: Trip): number => {
if (t.start_date && t.end_date && t.start_date <= today && t.end_date >= today) return 0
if (t.start_date && t.start_date >= today) return 1
return 2
}
const ranked = [...trips].sort((a, b) => {
const ra = relevance(a)
const rb = relevance(b)
if (ra !== rb) return ra - rb
// Upcoming: soonest first. Everything else: most recently started first.
return ra === 2
? (b.start_date ?? '').localeCompare(a.start_date ?? '')
: (a.start_date ?? '').localeCompare(b.start_date ?? '')
})
return ranked[0] ?? null
}
export const tripRepo = {
async list(): Promise<{ trips: Trip[]; archivedTrips: Trip[] }> {
@@ -25,6 +51,26 @@ export const tripRepo = {
)
},
/**
* The startup redirect asks for this on the very first paint, so it has to
* answer offline too — otherwise "open my active trip on startup" drops the
* user on the dashboard whenever the launch has no network.
*/
async active(): Promise<ActiveTripResponse> {
return onlineThenCache(
() => tripsApi.active(),
async () => {
const all = await offlineDb.trips.toArray()
const trip = pickActive(all.filter(t => !t.is_archived))
return {
trip: trip
? { id: trip.id, title: trip.title, start_date: trip.start_date, end_date: trip.end_date }
: null,
}
},
)
},
async get(tripId: number | string): Promise<{ trip: Trip }> {
return onlineThenCache(
async () => {
@@ -3,12 +3,11 @@ import { http, HttpResponse } from 'msw';
/**
* Third-party endpoints the app calls directly, rather than through /api.
*
* Without these the request leaves the runner: MSW is started with
* `onUnhandledRequest: 'warn'`, so an unmatched call is a warning and a live
* network round trip, not a failure. That is how the mobile FX widget reached
* api.frankfurter.dev from CI and settled its promise after the test
* environment was gone, surfacing as `window is not defined` attributed to
* whichever case happened to be running.
* Without these the call is refused: tests/setup.ts errors on an unhandled request to
* another origin. It used to warn and then perform the request, which is how the mobile
* FX widget reached api.frankfurter.dev from CI and settled its promise after the test
* environment was gone, surfacing as `window is not defined` attributed to whichever
* case happened to be running. Add the endpoint here rather than letting it out.
*
* An empty rate list is the shape the widget already handles: it seeds the
* base's own self-rate and renders with nothing else selectable.
@@ -360,6 +360,11 @@ describe('API client interceptors', () => {
await expect(backupApi.download('backup.zip')).resolves.toBeUndefined();
expect(createObjectURL).toHaveBeenCalled();
expect(clickSpy).toHaveBeenCalled();
// The shared helper appends the anchor (Firefox ignores a click on a
// detached one) and revokes the object URL a tick later, not in-line.
expect(revokeObjectURL).not.toHaveBeenCalled();
await new Promise(r => setTimeout(r, 150));
expect(revokeObjectURL).toHaveBeenCalled();
vi.restoreAllMocks();
@@ -1,4 +1,4 @@
// FE-COMP-I18NCTX-001 to FE-COMP-I18NCTX-017
// FE-COMP-I18NCTX-001 to FE-COMP-I18NCTX-017 (plus -003b / -013b)
import { act, render, screen, waitFor } from '@testing-library/react';
import { SUPPORTED_LANGUAGES, TranslationProvider, useTranslation } from '../../../src/i18n/TranslationContext';
import { TransHtml } from '../../../src/i18n/TransHtml';
@@ -51,6 +51,17 @@ describe('TranslationProvider', () => {
expect(screen.getByTestId('value').textContent).toContain('5');
});
it('FE-COMP-I18NCTX-003b: inserts a value containing $ patterns literally', () => {
render(
<TranslationProvider>
<Probe tKey="journey.frontpage.suggestionText" params={{ title: 'A$&B $1 $`' }} />
</TranslationProvider>,
);
// A trip really can be named this, and `$&` as a replacement string would
// paste the matched placeholder back in.
expect(screen.getByTestId('value').textContent).toContain('A$&B $1 $`');
});
it('FE-COMP-I18NCTX-004: defaults to English with the matching locale', () => {
render(<TranslationProvider><Probe tKey="common.save" /></TranslationProvider>);
expect(screen.getByTestId('language').textContent).toBe('en');
@@ -149,6 +160,16 @@ describe('tHtml', () => {
expect(raw).toContain('&lt;img');
});
it('FE-COMP-I18NCTX-013b: keeps $ patterns in an escaped value literal', () => {
render(
<TranslationProvider>
<HtmlProbe tKey="journey.frontpage.suggestionText" params={{ title: 'A$&B' }} />
</TranslationProvider>,
);
expect(screen.getByTestId('raw').textContent).toContain('A$&amp;B');
});
it('FE-COMP-I18NCTX-014: returns the key unchanged when it is unknown', () => {
render(<TranslationProvider><HtmlProbe tKey="nope.nope" /></TranslationProvider>);
expect(screen.getByTestId('raw').textContent).toBe('nope.nope');
@@ -77,6 +77,8 @@ vi.mock('../../../../src/mobile/screens/admin/MAdminAddonManager', () => ({
<button type="button" onClick={onToggleBagTracking}>toggle bag</button>
<span data-testid="chat-state">{String(collabFeatures.chat)}</span>
<button type="button" onClick={() => onToggleCollabFeature('chat')}>toggle chat</button>
<span data-testid="notes-state">{String(collabFeatures.notes)}</span>
<button type="button" onClick={() => onToggleCollabFeature('notes')}>toggle notes</button>
</div>
),
}));
@@ -362,6 +364,34 @@ describe('MAdmin', () => {
await waitFor(() => expect(screen.getByTestId('chat-state')).toHaveTextContent('true'));
});
it('FE-MOB-ADMIN-018: a failing toggle only rolls back its own key', async () => {
let releaseChat: () => void = () => {};
server.use(
http.put('/api/admin/collab-features', async ({ request }) => {
const body = (await request.json()) as Record<string, unknown>;
if ('chat' in body) {
await new Promise<void>((resolve) => { releaseChat = resolve; });
return HttpResponse.json({ error: 'boom' }, { status: 500 });
}
return HttpResponse.json({ ...body });
}),
);
renderAdmin();
await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument());
await openSection('Addons');
await waitFor(() => expect(screen.getByTestId('chat-state')).toHaveTextContent('true'));
fireEvent.click(screen.getByRole('button', { name: 'toggle chat' }));
fireEvent.click(screen.getByRole('button', { name: 'toggle notes' }));
await waitFor(() => expect(screen.getByTestId('notes-state')).toHaveTextContent('false'));
releaseChat();
// Chat comes back, but the notes toggle the admin made meanwhile survives.
await waitFor(() => expect(screen.getByTestId('chat-state')).toHaveTextContent('true'));
expect(screen.getByTestId('notes-state')).toHaveTextContent('false');
});
it('FE-MOB-ADMIN-017: the stats grid falls back to zero files', async () => {
server.use(
http.get('/api/admin/stats', () =>
@@ -44,6 +44,8 @@ vi.mock('../../../../src/components/shared/CustomSelect', () => ({
}));
const origCreateObjectURL = URL.createObjectURL;
const origRevokeObjectURL = URL.revokeObjectURL;
const revokeSpy = vi.fn();
function buildDashTrip(over: Partial<DashboardTrip> = {}): DashboardTrip {
return {
@@ -69,12 +71,15 @@ beforeEach(() => {
return 1;
}) as unknown as typeof window.__addToast;
URL.createObjectURL = (() => 'blob:preview') as unknown as typeof URL.createObjectURL;
revokeSpy.mockClear();
URL.revokeObjectURL = revokeSpy as unknown as typeof URL.revokeObjectURL;
useAuthStore.setState({ isAuthenticated: true, user: buildUser({ id: 1, role: 'user' }) });
usePermissionsStore.setState({ permissions: {} });
});
afterEach(() => {
URL.createObjectURL = origCreateObjectURL;
URL.revokeObjectURL = origRevokeObjectURL;
delete window.__addToast;
useSettingsStore.setState(s => ({ settings: { ...s.settings, default_currency: '' } }));
vi.restoreAllMocks();
@@ -374,6 +379,30 @@ describe('MNewTripSheet', () => {
expect(update).not.toHaveBeenCalled();
});
// The preview holds the whole picked file in memory until the url is released.
it('FE-MOB-NTSH-034: a replaced or dropped file preview releases its blob url', async () => {
render(<MNewTripSheet open trip={null} onClose={() => {}} onSave={() => {}} />);
fireEvent.change(fileInput(), { target: { files: [png()] } });
await waitFor(() => expect(screen.getByRole('button', { name: 'Delete' })).toBeInTheDocument());
expect(revokeSpy).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
await waitFor(() => expect(revokeSpy).toHaveBeenCalledWith('blob:preview'));
});
it('FE-MOB-NTSH-035: a stored cover url is never handed to revokeObjectURL', async () => {
const { unmount } = render(
<MNewTripSheet open trip={buildDashTrip()} onClose={() => {}} onSave={() => {}} />,
);
await waitFor(() =>
expect(document.querySelector('img[src="/uploads/covers/a.jpg"]')).toBeInTheDocument(),
);
unmount();
expect(revokeSpy).not.toHaveBeenCalled();
});
it('FE-MOB-NTSH-023: removing a stored cover clears it on the server', async () => {
const update = vi.spyOn(tripsApi, 'update').mockResolvedValue({ trip: { id: 42 } as Trip });
const onCoverUpdate = vi.fn();
@@ -629,6 +629,28 @@ describe('MJourneyDetail', () => {
expect(hook.updateEntry).toHaveBeenCalledWith(77, { title: 'Fresh' });
});
// Leaving the screen mid-probe used to leave the requests running and land a
// setState on a gone component.
it('FE-MOB-JDET-038: leaving the screen aborts the provider probes', async () => {
vi.mocked(addonsApi.enabled).mockResolvedValue({
addons: [{ id: 'immich', name: 'Immich', type: 'photo_provider', enabled: true }],
});
let signal: AbortSignal | undefined;
vi.stubGlobal('fetch', vi.fn(async (_url: string, init?: RequestInit) => {
signal = init?.signal ?? undefined;
return new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => reject(new Error('aborted')));
});
}));
const { unmount } = setup({ view: 'gallery' });
await waitFor(() => expect(signal).toBeDefined());
expect(signal!.aborted).toBe(false);
unmount();
expect(signal!.aborted).toBe(true);
});
it('FE-MOB-JDET-037: the screen measures itself, not the shell', () => {
// #1809: the shell scrolls with the document now and hands down no definite
// height. A map on a percentage of an auto-height parent collapses to zero.
@@ -1,3 +1,4 @@
import { StrictMode } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { http, HttpResponse } from 'msw';
import userEvent from '@testing-library/user-event';
@@ -244,6 +245,7 @@ interface MountOptions {
withDelete?: boolean;
withProviderHook?: boolean;
upload?: UploadFn;
strict?: boolean;
}
const defaultUpload: UploadFn = async (_entryId, files, cbs) => {
@@ -258,7 +260,7 @@ function mountSheet(sheetEntry: JourneyEntry, opts: MountOptions = {}) {
const onSave = vi.fn(async (_data: Record<string, unknown>, _existingEntryId?: number) => 42);
const onUploadPhotos = vi.fn(opts.upload ?? defaultUpload);
const onAddProviderPhotos = vi.fn(async (_entryId: number, _group: Record<string, unknown>) => {});
const view = render(
const sheet = (
<MJourneyEntrySheet
entry={sheetEntry}
galleryPhotos={opts.galleryPhotos ?? []}
@@ -274,6 +276,9 @@ function mountSheet(sheetEntry: JourneyEntry, opts: MountOptions = {}) {
onDone={onDone}
/>
);
// main.tsx runs the app inside StrictMode, so a handler that is not pure shows
// its double-invoke here and nowhere else.
const view = render(opts.strict ? <StrictMode>{sheet}</StrictMode> : sheet);
return { ...view, onClose, onDone, onDelete, onSave, onUploadPhotos, onAddProviderPhotos };
}
@@ -283,14 +288,20 @@ const timeField = () => document.querySelector('input[type="time"]') as HTMLInpu
const jpeg = (name = 'a.jpg') => new File(['x'], name, { type: 'image/jpeg' });
const originalCreateObjectURL = URL.createObjectURL;
const originalRevokeObjectURL = URL.revokeObjectURL;
const revokeSpy = vi.fn();
describe('MJourneyEntrySheet full editor', () => {
beforeEach(() => {
toastSpy.mockClear();
revokeSpy.mockClear();
window.__addToast = toastSpy;
Object.defineProperty(URL, 'createObjectURL', {
configurable: true, writable: true, value: vi.fn(() => 'blob:preview'),
});
Object.defineProperty(URL, 'revokeObjectURL', {
configurable: true, writable: true, value: revokeSpy,
});
});
afterEach(() => {
@@ -298,6 +309,9 @@ describe('MJourneyEntrySheet full editor', () => {
Object.defineProperty(URL, 'createObjectURL', {
configurable: true, writable: true, value: originalCreateObjectURL,
});
Object.defineProperty(URL, 'revokeObjectURL', {
configurable: true, writable: true, value: originalRevokeObjectURL,
});
});
it('FE-MOB-JENTRY-003: shows every editor section for a brand new entry', () => {
@@ -530,6 +544,22 @@ describe('MJourneyEntrySheet full editor', () => {
expect(document.querySelector('img[src="blob:preview"]')).not.toBeInTheDocument();
});
it('FE-MOB-JENTRY-048: mints one preview url per queued file and releases it on unmount', async () => {
const { unmount } = mountSheet(buildEntry());
fireEvent.change(multiFileInput(), { target: { files: [jpeg()] } });
await waitFor(() => expect(document.querySelector('img[src="blob:preview"]')).toBeInTheDocument());
expect(URL.createObjectURL).toHaveBeenCalledTimes(1);
// Typing re-renders the tile; the url must not be minted again.
fireEvent.change(screen.getByPlaceholderText('Give this moment a name...'), { target: { value: 'Ferry' } });
fireEvent.change(screen.getByPlaceholderText('Give this moment a name...'), { target: { value: 'Ferry day' } });
expect(URL.createObjectURL).toHaveBeenCalledTimes(1);
unmount();
expect(revokeSpy).toHaveBeenCalledWith('blob:preview');
});
it('FE-MOB-JENTRY-015: queues gallery photos on a new entry and links them after the save', async () => {
const linked: unknown[] = [];
server.use(http.post('/api/journeys/entries/42/link-photo', async ({ request }) => {
@@ -639,6 +669,24 @@ describe('MJourneyEntrySheet full editor', () => {
expect(order[0]).toBe('/api/photos/101/thumbnail');
});
it('FE-MOB-JENTRY-049: promoting a photo under StrictMode still patches each photo once', async () => {
const patched: Array<{ id: string; body: unknown }> = [];
server.use(http.patch('/api/journeys/photos/:id', async ({ params, request }) => {
patched.push({ id: String(params.id), body: await request.json() });
return HttpResponse.json({ ok: true });
}));
const user = userEvent.setup();
mountSheet(buildEntry({ id: 5, photos: [buildPhoto(100), buildPhoto(101)] }), { strict: true });
await user.click(screen.getByRole('button', { name: '1st' }));
await waitFor(() => expect(patched.length).toBeGreaterThanOrEqual(2));
// Let a doubled batch land before counting, otherwise the extra PATCHes slip in
// after the assertion.
await act(async () => { await new Promise(r => setTimeout(r, 20)); });
expect(patched.map(p => p.id)).toEqual(['101', '100']);
});
it('FE-MOB-JENTRY-021: toggles mood and weather chips back off', async () => {
const user = userEvent.setup();
const { onSave } = mountSheet(buildEntry({ id: 5, mood: 'rough', weather: 'cold' }));
@@ -267,7 +267,8 @@ describe('MJourneySettingsSheet', () => {
});
const create = vi.spyOn(journeyApi, 'createShareLink').mockResolvedValue({ token: 'tok-9' });
const writeText = vi.fn(async () => {});
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } });
Object.defineProperty(navigator, 'clipboard', { configurable: true, writable: true, value: { writeText } });
Object.defineProperty(window, 'isSecureContext', { configurable: true, writable: true, value: true });
setup();
expect(await screen.findByText(`${window.location.origin}/public/journey/tok-9`)).toBeInTheDocument();
@@ -370,6 +371,26 @@ describe('MJourneySettingsSheet', () => {
expect(props.onClose).toHaveBeenCalled();
});
// A self-hosted install served over plain HTTP has no navigator.clipboard, and the
// unguarded call used to throw before the button ever showed feedback.
it('FE-MOB-JSET-031: copies through execCommand when the clipboard API is unavailable', async () => {
vi.mocked(journeyApi.getShareLink).mockResolvedValue({
link: { token: 'tok-9', share_timeline: true, share_gallery: true, share_map: false },
});
Object.defineProperty(navigator, 'clipboard', { configurable: true, writable: true, value: undefined });
Object.defineProperty(window, 'isSecureContext', { configurable: true, writable: true, value: false });
const execCommand = vi.fn(() => true);
Object.defineProperty(document, 'execCommand', { configurable: true, writable: true, value: execCommand });
setup();
fireEvent.click(await screen.findByRole('button', { name: 'Copy' }));
await waitFor(() => expect(execCommand).toHaveBeenCalledWith('copy'));
expect(await screen.findByRole('button', { name: 'Copied!' })).toBeInTheDocument();
// The temporary textarea is removed again.
expect(document.querySelector('textarea')).toBeNull();
});
it('FE-MOB-JSET-030: an existing cover is shown instead of the gradient', async () => {
setup({ cover_image: 'covers/j.jpg' });
await waitFor(() =>
@@ -663,6 +663,28 @@ describe('MSettingsAccount – backup codes', () => {
openSpy.mockRestore();
});
// Parity with the desktop AccountTab: nothing reaches the popup unescaped, even
// though real codes are plain hex.
it('FE-MOB-SETACC-049: Print escapes the codes before writing them', async () => {
const user = userEvent.setup();
const written: string[] = [];
const popup = {
document: { open: vi.fn(), write: (html: string) => written.push(html), close: vi.fn() },
focus: vi.fn(),
print: vi.fn(),
};
const openSpy = vi.spyOn(window, 'open').mockReturnValue(popup as unknown as Window);
sessionStorage.setItem(BACKUP_KEY, JSON.stringify(['<img src=x onerror=alert(1)>']));
renderAccount();
await user.click(await screen.findByRole('button', { name: 'Print / PDF' }));
const html = written.join('');
expect(html).not.toContain('<img src=x');
expect(html).toContain('&lt;img src=x onerror=alert(1)&gt;');
openSpy.mockRestore();
});
it('FE-MOB-SETACC-046: a blocked popup leaves printing a no-op', async () => {
const user = userEvent.setup();
const openSpy = vi.spyOn(window, 'open').mockReturnValue(null);
@@ -386,7 +386,9 @@ describe('MSettingsAppearance', () => {
);
});
it('FE-MOB-SETAPP-027: unmounting before the debounce fires cancels the pending save', async () => {
// The scheme is already on the DOM by then, so dropping the write would revert the
// choice on the next load without ever telling the user.
it('FE-MOB-SETAPP-027: unmounting before the debounce fires flushes the pending save once', async () => {
const user = userEvent.setup();
const updateSetting = seedAppearance(undefined);
const { unmount } = renderAppearance();
@@ -394,7 +396,23 @@ describe('MSettingsAppearance', () => {
await user.click(screen.getByRole('button', { name: 'Indigo' }));
unmount();
expect(appearanceCalls(updateSetting)).toHaveLength(1);
expect(appearanceCalls(updateSetting)[0].schemeId).toBe('indigo');
// The timer is cancelled, so nothing lands a second time.
await new Promise((resolve) => setTimeout(resolve, 500));
expect(appearanceCalls(updateSetting)).toHaveLength(0);
expect(appearanceCalls(updateSetting)).toHaveLength(1);
});
it('FE-MOB-SETAPP-028: a debounce that already fired is not written again on unmount', async () => {
const user = userEvent.setup();
const updateSetting = seedAppearance(undefined);
const { unmount } = renderAppearance();
await user.click(screen.getByRole('button', { name: 'Teal' }));
await waitFor(() => expect(appearanceCalls(updateSetting)).toHaveLength(1));
unmount();
expect(appearanceCalls(updateSetting)).toHaveLength(1);
});
});
@@ -504,6 +504,43 @@ describe('MSettingsNotifications', () => {
await waitFor(() => expect(screen.getByRole('button', { name: 'In-App' }).className).toBe(activeClass));
});
it('FE-MOB-SETNOTIF-032: a failing update toasts and leaves a later toggle alone', async () => {
const user = userEvent.setup();
let rejectInapp!: () => void;
server.use(
http.put('/api/notifications/preferences', async ({ request }) => {
const body = (await request.json()) as Record<string, Record<string, boolean>>;
// The first write is the in-app flip; it hangs until the test rejects it.
if (body.trip_invite.webhook === false) {
return new Promise<Response>(resolve => {
rejectInapp = () => resolve(HttpResponse.json({ error: 'nope' }, { status: 500 }) as unknown as Response);
});
}
return HttpResponse.json({ success: true });
}),
);
render(<><ToastContainer /><MSettingsNotifications /></>);
const inapp = await screen.findByRole('button', { name: 'In-App' });
// The webhook chip is off in this matrix — its look is the "inactive" reference.
const inactiveClass = screen.getByRole('button', { name: 'Webhook' }).className;
const activeClass = inapp.className;
await user.click(inapp);
await waitFor(() => expect(screen.getByRole('button', { name: 'In-App' }).className).toBe(inactiveClass));
// Flipped while the in-app write is still hanging.
await user.click(screen.getByRole('button', { name: 'Webhook' }));
await waitFor(() => expect(screen.getByRole('button', { name: 'Webhook' }).className).toBe(activeClass));
rejectInapp();
expect(await screen.findByText('Error')).toBeInTheDocument();
await waitFor(() => expect(screen.getByRole('button', { name: 'In-App' }).className).toBe(activeClass));
// The webhook toggle the user made meanwhile is not undone.
expect(screen.getByRole('button', { name: 'Webhook' }).className).toBe(activeClass);
});
it('FE-MOB-SETNOTIF-029: the saving hint shows while the update is in flight', async () => {
const user = userEvent.setup();
let release!: () => void;
@@ -5,6 +5,7 @@ import { clearExchangeRateCache } from '../../../../src/hooks/useExchangeRates'
import { useTripStore, type TripStoreState } from '../../../../src/store/tripStore'
import type { BudgetItem, BudgetItemMember } from '../../../../src/types'
import { buildBudgetItem } from '../../../helpers/factories'
import { localToday } from '../../../../src/components/Planner/today'
import { resetAllStores } from '../../../helpers/store'
import { act, fireEvent, render, screen, waitFor } from '../../../helpers/render'
@@ -17,7 +18,8 @@ const PEOPLE = [
{ id: 2, username: 'bob', avatar_url: null },
] as TripMember[]
const TODAY = new Date().toISOString().slice(0, 10)
// The traveller's own calendar day, not the UTC one — see components/Planner/today.ts.
const TODAY = localToday()
function member(user_id: number, amount: number | null): BudgetItemMember {
return { user_id, paid: 0, username: user_id === 1 ? 'alice' : 'bob', amount }
@@ -572,6 +574,32 @@ describe('MCostSheet', () => {
expect(screen.getByText('Guest')).toBeInTheDocument()
})
// #1567 all over again: an expense entered at 23:00 in Tokyo belongs on that
// evening's day, not on the UTC date that has not started there yet.
it('FE-MOB-COSTSH-031: the default expense date comes off the local clock, not UTC', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
try {
// East of Greenwich the two dates part just after midnight, west of it just
// before, so pick the edge that this runner's zone actually has.
const hour = new Date(2026, 7, 12).getTimezoneOffset() > 0 ? 23 : 0
const now = new Date(2026, 7, 12, hour, 30, 0)
vi.setSystemTime(now)
const { onSaved } = renderSheet()
fillBasics('Ramen', '12')
fireEvent.click(submit())
await waitFor(() => expect(addBudgetItem).toHaveBeenCalledTimes(1))
expect(addBudgetItem.mock.calls[0][1]).toMatchObject({ expense_date: '2026-08-12' })
// Guard the guard: in a UTC runner there is no drift to catch.
if (now.getTimezoneOffset() !== 0) {
expect(now.toISOString().slice(0, 10)).not.toBe('2026-08-12')
}
await waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1))
} finally {
vi.useRealTimers()
}
})
it('FE-MOB-COSTSH-030: a currency without a known symbol falls back to its code', () => {
localStorage.setItem('trek_fx_XTS', JSON.stringify({ rates: { XTS: 1 }, ts: Date.now() }))
renderSheet({ base: 'XTS' })
@@ -205,4 +205,27 @@ describe('MFileLightbox', () => {
fireEvent.click(screen.getByTestId('video-player').parentElement as HTMLElement)
expect(onClose).not.toHaveBeenCalled()
})
// Swiping is quicker than the token round trip, so the first file's url must not
// land on the second one.
it('FE-MOB-FLBOX-018: a token that resolves after a swipe does not overwrite the new image', async () => {
const release: Array<(url: string) => void> = []
vi.mocked(getAuthUrl).mockImplementation(
(url: string) => new Promise<string>(resolve => { release.push(() => resolve(`${url}?token=t1`)) }),
)
const { rerender, onIndexChange, onClose } = renderBox(0)
rerender(
<MFileLightbox files={FILES} index={1} onIndexChange={onIndexChange} onClose={onClose} t={t} />,
)
await waitFor(() => expect(release).toHaveLength(2))
// The first file resolves last.
release[1]('')
release[0]('')
await waitFor(() =>
expect(screen.getByAltText('castle.png')).toHaveAttribute('src', '/api/trips/1/files/2/download?token=t1'),
)
})
})
@@ -718,6 +718,27 @@ describe('MReservationSheet', () => {
expect(selects()[2]).toHaveAttribute('data-value', '13')
})
// A legacy or corrupted metadata column used to throw straight out of the open
// effect and leave the sheet blank.
it('FE-MOB-RESSH-052: unparseable metadata opens the sheet with empty check-in times', () => {
setup(makePlanner({
editingReservation: { ...DINNER, type: 'hotel', metadata: '{not json' },
}))
expect(titleField()).toHaveValue('Dinner')
expect(screen.getByPlaceholderText('15:00')).toHaveValue('')
})
it('FE-MOB-RESSH-053: double-encoded metadata still fills the check-in times', () => {
setup(makePlanner({
editingReservation: {
...DINNER, type: 'hotel',
metadata: JSON.stringify(JSON.stringify({ check_in_time: '16:00', check_out_time: '10:30' })),
},
}))
expect(screen.getByPlaceholderText('15:00')).toHaveValue('16:00')
expect(screen.getByPlaceholderText('11:00')).toHaveValue('10:30')
})
it('FE-MOB-RESSH-051: a hotel place without an address keeps the typed one', () => {
setup()
fireEvent.click(screen.getByRole('button', { name: 'reservations.type.hotel' }))
@@ -371,6 +371,30 @@ describe('costsModel — CSV export', () => {
expect(filename).toBe('costs-trip.csv');
});
it('FE-MOB-CMOD-028: prefixes formula-leading names and notes so spreadsheets keep them as text', () => {
const items = [
expense({
id: 46,
name: '=HYPERLINK("http://evil","click")',
category: 'food',
expense_date: null,
total_price: 5,
note: '@SUM(A1:A9)',
}),
expense({ id: 47, name: '-12 refund', category: 'other', expense_date: null, total_price: 5 }),
];
const { content } = buildCostsCsv(items, { base: 'EUR', ctx, locale: 'en-US', tripTitle: null, t });
const rows = content.split('\r\n');
// The quote inside the name still forces the field to be quoted around the apostrophe.
expect(rows[1]).toContain(`"'=HYPERLINK(""http://evil"",""click"")"`);
expect(rows[1]).toContain("'@SUM(A1:A9)");
expect(rows[2]).toContain("'-12 refund");
// Numbers never go through the escaper, so the amount columns stay parseable.
expect(rows[2]).toContain(';5.00;EUR;5.00;');
});
it('FE-MOB-CMOD-024: falls back to the raw ISO date when the locale is unusable', () => {
const { content } = buildCostsCsv(
[expense({ id: 44, name: 'Bus', category: 'transport', expense_date: '2026-07-16', total_price: 3 })],
+33 -1
View File
@@ -138,17 +138,49 @@ describe('dayNotesSlice', () => {
const note = buildDayNote({ id: 10, day_id: 1, text: 'Move me' });
seedStore(useTripStore, { dayNotes: { '1': [note], '2': [] } });
let deleted = false;
server.use(
http.delete('/api/trips/1/days/1/notes/10', () =>
http.post('/api/trips/1/days/2/notes', () =>
HttpResponse.json({ message: 'Error' }, { status: 500 })
),
http.delete('/api/trips/1/days/1/notes/10', () => {
deleted = true;
return HttpResponse.json({ success: true });
}),
);
await expect(useTripStore.getState().moveDayNote(1, 1, 2, 10)).rejects.toThrow();
// The create is the first half of the move, so a failure there must leave
// the note where it was instead of deleting it out from under the user.
expect(deleted).toBe(false);
expect(useTripStore.getState().dayNotes['1']).toHaveLength(1);
expect(useTripStore.getState().dayNotes['1'][0].id).toBe(10);
});
it('FE-DAYNOTES-006b: moveDayNote removes the copy again when the source delete fails', async () => {
const note = buildDayNote({ id: 10, day_id: 1, text: 'Move me' });
const newNote = buildDayNote({ id: 99, day_id: 2, text: 'Move me' });
seedStore(useTripStore, { dayNotes: { '1': [note], '2': [] } });
const deletedFromTarget: number[] = [];
server.use(
http.post('/api/trips/1/days/2/notes', () => HttpResponse.json({ note: newNote })),
http.delete('/api/trips/1/days/1/notes/10', () =>
HttpResponse.json({ message: 'Error' }, { status: 500 })
),
http.delete('/api/trips/1/days/2/notes/:noteId', ({ params }) => {
deletedFromTarget.push(Number(params.noteId));
return HttpResponse.json({ success: true });
}),
);
await expect(useTripStore.getState().moveDayNote(1, 1, 2, 10)).rejects.toThrow();
expect(deletedFromTarget).toEqual([99]);
expect(useTripStore.getState().dayNotes['1']).toHaveLength(1);
expect(useTripStore.getState().dayNotes['2']).toHaveLength(0);
});
});
describe('updateDayNotes', () => {
@@ -10,6 +10,15 @@ import { buildUser } from '../../helpers/factories';
// The websocket module is already mocked globally in tests/setup.ts
import { connect, disconnect } from '../../../src/api/websocket';
// authStore is the only consumer of these two, so stubbing the module keeps the
// real 30s interval and window listeners out of the suite while still letting us
// assert the register/unregister ordering around a logout.
const syncTriggers = vi.hoisted(() => ({
registerSyncTriggers: vi.fn(),
unregisterSyncTriggers: vi.fn(),
}));
vi.mock('../../../src/sync/syncTriggers', () => syncTriggers);
// The user-scoped offline DB is real (fake-indexeddb); only the reopen step is
// made failable so the "auth still succeeds when the DB won't open" path runs.
const dbControl = vi.hoisted(() => ({ reopenFails: false }));
@@ -732,4 +741,22 @@ describe('authStore', () => {
expect(state.placesDetailsEnabled).toBe(false);
});
});
describe('FE-STORE-AUTH-033: logging in again after a logout', () => {
it('re-registers the sync triggers logout tore down', async () => {
const user = buildUser();
server.use(
http.post('/api/auth/login', () => HttpResponse.json({ user, token: 'tok' }))
);
useAuthStore.setState({ user, isAuthenticated: true });
await useAuthStore.getState().logout();
expect(syncTriggers.unregisterSyncTriggers).toHaveBeenCalled();
syncTriggers.registerSyncTriggers.mockClear();
await useAuthStore.getState().login(user.email, 'password');
expect(syncTriggers.registerSyncTriggers).toHaveBeenCalled();
});
});
});
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import type { BookElement } from '@trek/shared'
import type { BookElement, JourneyStats } from '@trek/shared'
import { bookPageSetupSchema } from '@trek/shared'
import { applyTemplate, templateFit, type TemplateEntry } from '../../../src/components/Studio/applyTemplate'
import type { SpreadTemplate } from '../../../src/components/Studio/bookTemplates.data'
@@ -110,6 +110,14 @@ describe('what gets filled', () => {
expect((spread.elements[0] as { text: string }).text).toBe('DAY 1')
})
/* Every other figure on the page follows the book language; so does this one. */
it('sets the distance in the book language', () => {
const mark = el({ kind: 'badge', variant: 'distance', text: '', sub: '', code: null, style: 'plain' })
const travelled = { distance: 1_189_000, countries: [] } as unknown as JourneyStats
const spread = applyTemplate(template([mark]), entry(), { ...ctx, locale: 'de', stats: travelled })
expect((spread.elements[0] as { text: string }).text).toBe('1.189 km')
})
it('belongs to the entry it was filled from', () => {
expect(applyTemplate(template([titleEl]), entry(), ctx).entryId).toBe(7)
})
@@ -197,6 +197,16 @@ describe('the back cover', () => {
expect(el.opacity).toBeLessThan(1)
})
/*
* places and steps are separate figures — a journal with entries but no
* linked trip has steps and no places at all, and the tile printed "0".
*/
it('leaves out the places tally when the journey has none', () => {
const back = last(build({ stats: stats({ places: 0, steps: 4 }) }).spreads)
const el = back.elements.find(e => e.kind === 'stats')!
expect(el.kind === 'stats' && el.metrics).not.toContain('places')
})
it('still closes the book when there are no figures', () => {
const back = last(build({ stats: null }).spreads)
expect(back.role).toBe('back')
@@ -110,6 +110,41 @@ describe('a locked element', () => {
expect(container.querySelectorAll('.st-select')).toHaveLength(1)
})
/*
* Delete was the one gesture that ignored the flag: the element was still
* selectable, so a stray Delete took away exactly what had been pinned down.
*/
it('is not deleted by the Delete key', () => {
load(shape({ locked: true }))
const { container } = draw()
fireEvent.pointerDown(hitTarget(container))
fireEvent.keyDown(document, { key: 'Delete' })
expect(useStudioStore.getState().doc!.spreads[0].elements).toHaveLength(1)
})
it('is not deleted by the quick bar either', () => {
load(shape({ locked: true }))
const { container, getByTitle } = draw()
fireEvent.pointerDown(hitTarget(container))
fireEvent.pointerUp(container.querySelector('.st-stage')!)
fireEvent.click(getByTitle('Delete'))
expect(useStudioStore.getState().doc!.spreads[0].elements).toHaveLength(1)
})
it('leaves an unlocked element deletable', () => {
load(shape({ locked: false }))
const { container } = draw()
fireEvent.pointerDown(hitTarget(container))
fireEvent.keyDown(document, { key: 'Delete' })
expect(useStudioStore.getState().doc!.spreads[0].elements).toHaveLength(0)
})
it('leaves an unlocked element movable, with its handles', () => {
load(shape({ locked: false }))
const { container } = draw()
+42 -2
View File
@@ -1,8 +1,10 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type { BookElement, BookPageSetup, BookSpread } from '@trek/shared'
import type { BookDocument, BookElement, BookPageSetup, BookSpread, JourneyStats } from '@trek/shared'
import { bookPageSetupSchema } from '@trek/shared'
import { render } from '../../helpers/render'
import { fireEvent, render } from '../../helpers/render'
import { SpreadView } from '../../../src/components/Studio/SpreadView'
import { StudioTravelPanel } from '../../../src/components/Studio/StudioTravelPanel'
import { useStudioStore } from '../../../src/store/studioStore'
import { fetchRoads } from '../../../src/components/Studio/roadRoute'
vi.mock('../../../src/components/Map/RouteCalculator', () => ({
@@ -216,3 +218,41 @@ describe('what gets asked for', () => {
expect(roads[0]!.length).toBe(40)
})
})
/**
* The lookups outlive the click by design — they are paced so the router is not
* hammered — so the panel has to take them with it when it goes.
*/
describe('placing a map from the panel', () => {
const journeyStats = {
journeyId: 1, distance: 0, days: 1, steps: 3, photos: 0, places: 3, furthest: 0,
countries: [], trips: [], start: null, end: null,
points: STOPS.map(p => ({ ...p, date: null, country: null, tripId: null })),
} as unknown as JourneyStats
beforeEach(() => {
vi.mocked(calculateRouteWithLegs).mockReset()
useStudioStore.getState().load({
version: 1, title: 'T', page,
spreads: [{ id: 's1', role: 'inner', background: null, elements: [], parked: [], entryId: null }],
} as unknown as BookDocument)
})
it('drops the road lookup when the panel goes away', async () => {
let asked: AbortSignal | undefined
vi.mocked(calculateRouteWithLegs).mockImplementation((_stops, opts) => {
asked = (opts as { signal?: AbortSignal } | undefined)?.signal
return new Promise(() => {}) as never
})
const { getByTitle, unmount } = render(
<StudioTravelPanel page={page} stats={journeyStats} path={[]} t={k => k} locale="en" />,
)
fireEvent.click(getByTitle('journey.studio.mapStyle.minimal'))
await vi.waitFor(() => expect(calculateRouteWithLegs).toHaveBeenCalled())
unmount()
expect(asked?.aborted).toBe(true)
})
})
+45 -4
View File
@@ -368,11 +368,55 @@ describe('conflicts', () => {
expect(result.current.state.status).toBe('conflict')
api.saveBook.mockResolvedValue(record({ version: 7 }))
// Choosing re-sends what was refused, so this is the third write, not the second.
act(() => { result.current.keepMine(theirs) })
await tick()
act(() => { result.current.queueSave(doc('mine again'), 'T') })
await tick()
expect(api.saveBook).toHaveBeenCalledTimes(3)
})
/*
* The one that lost an afternoon: write() empties the queue before it makes
* the request, so after a 409 nothing is queued. "Keep mine" cleared the
* conflict and left the document unsent until the user happened to touch the
* book again — and closing the editor writes the queue, which was empty.
*/
it('sends the refused document as soon as the local one is kept', async () => {
const theirs = record({ version: 6 })
api.saveBook.mockRejectedValueOnce(conflictError(theirs))
const { result } = await mount()
act(() => { result.current.queueSave(doc('mine'), 'T') })
await tick()
expect(result.current.state.status).toBe('conflict')
api.saveBook.mockResolvedValue(record({ version: 7 }))
act(() => { result.current.keepMine(theirs) })
await tick()
expect(api.saveBook).toHaveBeenCalledTimes(2)
expect(api.saveBook.mock.calls[1][1]).toMatchObject({ title: 'T', baseVersion: 6 })
expect((api.saveBook.mock.calls[1][1].document as BookDocument).title).toBe('mine')
expect(result.current.state.status).toBe('saved')
})
/* Nothing of their own to send: keeping theirs-as-mine is just the version. */
it('only clears the conflict when the local document is the agreed one', async () => {
const theirs = record({ version: 6 })
api.saveBook.mockRejectedValueOnce(conflictError(theirs))
const { result } = await mount()
act(() => { result.current.queueSave(doc('mine'), 'T') })
await tick()
act(() => { result.current.acceptTheirs(theirs) })
act(() => { result.current.keepMine(theirs) })
await tick()
expect(api.saveBook).toHaveBeenCalledTimes(1)
expect(result.current.state.status).toBe('idle')
})
it('returns their document when their version is taken, and drops the pending write', async () => {
@@ -408,11 +452,8 @@ describe('conflicts', () => {
await tick()
expect(result.current.state.status).toBe('conflict')
act(() => { result.current.keepMine(theirs) })
expect(result.current.state.status).toBe('idle')
api.saveBook.mockResolvedValue(record({ version: 7 }))
act(() => { result.current.queueSave(doc('mine again'), 'T') })
act(() => { result.current.keepMine(theirs) })
await tick()
expect(api.saveBook.mock.calls[1][1].baseVersion).toBe(6)
+94 -2
View File
@@ -22,11 +22,12 @@ import {
buildTripFile,
} from '../../helpers/factories';
// Helper to get today ± N days as YYYY-MM-DD
// Helper to get today ± N days as YYYY-MM-DD. Local calendar date, like the
// manager itself, so the ±1-day boundary cases hold outside UTC too.
function dateOffset(days: number): string {
const d = new Date();
d.setDate(d.getDate() + days);
return d.toISOString().slice(0, 10);
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}
function makeBundle(tripId: number) {
@@ -283,3 +284,94 @@ describe('tripSyncManager — file blob caching', () => {
expect(cached.length).toBe(0);
});
});
// ── local calendar dates ───────────────────────────────────────────────────────
describe('tripSyncManager.syncAll — local calendar dates', () => {
// Only Date is faked; Dexie and MSW keep their real timers.
const withClock = (tz: string, iso: string, run: () => Promise<void>) => async () => {
const prevTz = process.env.TZ;
process.env.TZ = tz;
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date(iso));
try {
await run();
} finally {
vi.useRealTimers();
if (prevTz === undefined) delete process.env.TZ;
else process.env.TZ = prevTz;
}
};
it('caches a trip on its last evening west of UTC', withClock(
'America/Los_Angeles',
// 21:00 on the 22nd in Los Angeles is already the 23rd in UTC.
'2026-08-23T04:00:00Z',
async () => {
const tripId = 110;
const trip = buildTrip({ id: tripId, end_date: '2026-08-22' });
const bundle = { ...makeBundle(tripId), trip };
server.use(
http.get('/api/trips', () => HttpResponse.json({ trips: [trip] })),
http.get(`/api/trips/${tripId}/bundle`, () => HttpResponse.json(bundle)),
);
await tripSyncManager.syncAll();
expect(await offlineDb.trips.get(tripId)).toBeDefined();
},
));
it('drops a trip that ended yesterday east of UTC', withClock(
'Asia/Tokyo',
// 08:00 on the 23rd in Tokyo is still the 22nd in UTC.
'2026-08-22T23:00:00Z',
async () => {
const tripId = 111;
const trip = buildTrip({ id: tripId, end_date: '2026-08-22' });
let bundleCalled = false;
server.use(
http.get('/api/trips', () => HttpResponse.json({ trips: [trip] })),
http.get(`/api/trips/${tripId}/bundle`, () => {
bundleCalled = true;
return HttpResponse.json({});
}),
);
await tripSyncManager.syncAll();
expect(bundleCalled).toBe(false);
expect(await offlineDb.trips.get(tripId)).toBeUndefined();
},
));
});
// ── logout mid-sync ────────────────────────────────────────────────────────────
describe('tripSyncManager.syncAll — logout while syncing', () => {
it('stops writing trips once the gate closes mid-loop', async () => {
const firstId = 500;
const secondId = 501;
const first = buildTrip({ id: firstId, end_date: dateOffset(5) });
const second = buildTrip({ id: secondId, end_date: dateOffset(5) });
let secondBundleCalled = false;
server.use(
http.get('/api/trips', () => HttpResponse.json({ trips: [first, second] })),
http.get(`/api/trips/${firstId}/bundle`, () => {
// The user logs out while the first bundle is on the wire.
setAuthed(false);
return HttpResponse.json({ ...makeBundle(firstId), trip: first });
}),
http.get(`/api/trips/${secondId}/bundle`, () => {
secondBundleCalled = true;
return HttpResponse.json({ ...makeBundle(secondId), trip: second });
}),
);
await tripSyncManager.syncAll();
expect(secondBundleCalled).toBe(false);
expect(await offlineDb.trips.get(secondId)).toBeUndefined();
});
});