chore(deps-dev): bump msw from 2.15.0 to 3.0.8 and move the client tests to it

msw 3 renames onUnhandledRequest to onUnhandledFrame and reports every
network frame there; the setup judges the HTTP frames as before (another
origin is an error, the page's own a warning).

It also resolves a relative handler, and its fetch interceptor a
relative URL, against location.href at the time of the request, while
jsdom's XHR sends to the document's own address. Tests that replaced
window.location with a stand-in on http://localhost while the page runs
on http://localhost:3000 sent their requests past every handler.
tests/helpers/location.ts builds such stand-ins on the page's own origin
(locationAt, pageUrl), and every one of them now uses it.

msw no longer escapes fake timers, and responses are timed differently,
which surfaced tests that ended with work still running: a held request
answering in the next test, a lookup still out when the assertions ran,
a reload switched by counting reads. Each of those now waits for, or
releases, what it started, and answers by what happened rather than by
a count.

The day panel suites share their setup through
tests/helpers/dayDetailPanel.ts instead of a copy each, which keeps the
larger one under its size limit.
This commit is contained in:
Maurice
2026-11-26 13:15:45 +01:00
parent 05f4c84885
commit 32837afe2e
24 changed files with 493 additions and 434 deletions
+1 -1
View File
@@ -154,7 +154,7 @@
"eslint-plugin-react-refresh": "^0.5.8",
"fake-indexeddb": "^6.2.7",
"jsdom": "^29.1.1",
"msw": "^2.15.0",
"msw": "^3.0.8",
"postcss": "^8.5.33",
"prettier": "^3.10.1",
"prettier-plugin-organize-imports": "^4.3.0",
+1 -1
View File
@@ -8,7 +8,7 @@
"src/components/Map/MapView.tsx": 1200,
"src/components/Map/MapViewGL.test.tsx": 2919,
"src/components/Map/MapViewGL.tsx": 2116,
"src/components/Planner/DayDetailPanel.test.tsx": 2333,
"src/components/Planner/DayDetailPanel.test.tsx": 2332,
"src/components/Planner/DayPlanSidebar.test.tsx": 5349,
"src/components/Planner/DayPlanSidebar.tsx": 2908,
"src/components/Planner/PlaceFormModal.test.tsx": 2836,
+28 -4
View File
@@ -1,13 +1,14 @@
import React from 'react'
import { render, screen, waitFor, act } from '@testing-library/react'
import { MemoryRouter, useLocation } from 'react-router'
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { describe, it, expect, beforeEach, onTestFinished, vi } from 'vitest'
import { http, HttpResponse } from 'msw'
import { server } from '../tests/helpers/msw/server'
import { useAuthStore } from './store/authStore'
import { useSettingsStore } from './store/settingsStore'
import { resetAllStores } from '../tests/helpers/store'
import { buildUser, buildSettings, buildTrip } from '../tests/helpers/factories'
import { locationAt } from '../tests/helpers/location'
import { offlineDb } from './db/offlineDb'
import { SETTINGS_WAIT_MS } from './utils/startDestination'
import App from './App'
@@ -185,9 +186,29 @@ describe('RootRedirect — startup destination', () => {
seedAuth({ isAuthenticated: true, user: buildUser() })
useSettingsStore.setState({ isLoaded: false })
stubActiveTrip({ id: 42, title: 'Japan' })
// App asks for the settings on its own as soon as the user is signed in.
// Held until the redirect is decided, or whichever answer lands first wins
// and the test proves nothing about the mirror; released here, so it cannot
// land in the next test either.
let releaseSettings = () => {}
const settingsHeld = new Promise<void>((resolve) => { releaseSettings = resolve })
onTestFinished(() => releaseSettings())
server.use(
http.get('/api/settings', async () => {
await settingsHeld
return HttpResponse.json({
settings: buildSettings({ start_page: 'active_trip', start_trip_tab: 'finanzplan' }),
})
}),
)
renderApp('/')
await waitFor(() => expect(screen.getByText('TripPlanner')).toBeInTheDocument())
expect(currentPath()).toBe('/trips/42?tab=finanzplan')
expect(useSettingsStore.getState().isLoaded).toBe(false)
releaseSettings()
await waitFor(() => expect(useSettingsStore.getState().isLoaded).toBe(true))
})
})
@@ -532,7 +553,7 @@ describe('Version cache-busting', () => {
const reload = vi.fn()
Object.defineProperty(window, 'location', {
writable: true,
value: { ...window.location, reload },
value: locationAt('/', { reload }),
})
server.use(
@@ -587,7 +608,7 @@ describe('Version cache-busting', () => {
// and try to update.
localStorage.setItem('trek_app_version', '2.9.9')
const reload = vi.fn()
Object.defineProperty(window, 'location', { writable: true, value: { ...window.location, reload } })
Object.defineProperty(window, 'location', { writable: true, value: locationAt('/', { reload }) })
server.use(
http.get('/api/auth/app-config', () =>
@@ -609,7 +630,7 @@ describe('Version cache-busting', () => {
// failure neither deletes anything nor reloads into the old worker's shell.
localStorage.setItem('trek_app_version', '2.9.9')
const reload = vi.fn()
Object.defineProperty(window, 'location', { writable: true, value: { ...window.location, reload } })
Object.defineProperty(window, 'location', { writable: true, value: locationAt('/', { reload }) })
const cachesDelete = vi.fn().mockResolvedValue(true)
const unregister = vi.fn().mockResolvedValue(true)
vi.stubGlobal('caches', { keys: vi.fn().mockResolvedValue(['workbox-precache-v2', 'map-tiles']), delete: cachesDelete })
@@ -685,6 +706,9 @@ describe('RootRedirect — preference not mirrored on this device', () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
seedAuth({ isAuthenticated: true, user: buildUser() })
useSettingsStore.setState({ isLoaded: false })
// No backend: the settings never arrive, so only the timeout can decide.
// Answered, they would open the dashboard on their own and hide the wait.
server.use(http.get('/api/settings', () => HttpResponse.error()))
renderApp('/')
expect(screen.queryByText('Dashboard')).not.toBeInTheDocument()
@@ -341,12 +341,14 @@ describe('DefaultUserSettingsTab', () => {
expect(input).toHaveValue('pk.old');
await user.clear(input);
await user.type(input, 'pk.new');
fireEvent.blur(input);
// Leave the field for real: fireEvent.blur keeps the focus on it, so the reset click
// would blur it a second time and race that save against the reset request
await user.tab();
expect(input).not.toHaveFocus();
await waitFor(() => expect(puts).toEqual([{ mapbox_access_token: 'pk.new' }]));
// Clicking the reset link also blurs the field again, so only the last PUT is checked
await user.click(resetLink('Shared Mapbox token'));
await waitFor(() => expect(puts[puts.length - 1]).toEqual({ mapbox_access_token: null }));
await waitFor(() => expect(puts).toEqual([{ mapbox_access_token: 'pk.new' }, { mapbox_access_token: null }]));
await waitFor(() => expect(screen.getByPlaceholderText('pk.eyJ…')).toHaveValue(''));
});
@@ -449,12 +451,14 @@ describe('DefaultUserSettingsTab', () => {
expect(input).toHaveValue('ck.old');
await user.clear(input);
await user.type(input, 'ck.new');
fireEvent.blur(input);
// Leave the field for real: fireEvent.blur keeps the focus on it, so the reset click
// would blur it a second time and race that save against the reset request
await user.tab();
expect(input).not.toHaveFocus();
await waitFor(() => expect(puts).toEqual([{ carto_api_key: 'ck.new' }]));
// Clicking the reset link also blurs the field again, so only the last PUT is checked
await user.click(resetLink('Shared CARTO key'));
await waitFor(() => expect(puts[puts.length - 1]).toEqual({ carto_api_key: null }));
await waitFor(() => expect(puts).toEqual([{ carto_api_key: 'ck.new' }, { carto_api_key: null }]));
await waitFor(() => expect(cartoInput()).toHaveValue(''));
});
@@ -11,6 +11,39 @@ import DevNotificationsPanel from './DevNotificationsPanel';
const ADMIN_USER = buildUser({ id: 1, username: 'testadmin', role: 'admin' });
/**
* Renders the panel and waits until both lookups (trips and users) have landed, so a test
* acts on the settled panel and no lookup answers after it has ended.
*/
async function renderSettled() {
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events');
await screen.findByText('User-Scoped Events');
}
const LOOKUPS = ['/api/admin/users', '/api/trips'];
/**
* Records the GET requests to `paths` that have been answered, for the tests whose lookups
* come back empty or failed and so change nothing on screen to wait for. Call before render;
* the returned function waits until exactly `paths` (a path once per expected request) ended.
*/
function trackRequests(paths: string[] = LOOKUPS) {
const answered: string[] = [];
const onEnd = ({ request }: { request: Request }) => {
const { pathname } = new URL(request.url);
if (request.method === 'GET' && paths.includes(pathname)) answered.push(pathname);
};
server.events.on('request:end', onEnd);
return async () => {
try {
await waitFor(() => expect([...answered].sort()).toEqual([...paths].sort()));
} finally {
server.events.removeListener('request:end', onEnd);
}
};
}
beforeEach(() => {
resetAllStores();
seedStore(useAuthStore, { user: ADMIN_USER, isAuthenticated: true });
@@ -21,9 +54,12 @@ afterEach(() => {
});
describe('DevNotificationsPanel', () => {
it('FE-ADMIN-DEVNOTIF-001: "DEV ONLY" badge is always visible', () => {
it('FE-ADMIN-DEVNOTIF-001: "DEV ONLY" badge is always visible', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>);
expect(screen.getByText('DEV ONLY')).toBeInTheDocument();
// Let the lookups the panel started land here, not in the next test
await screen.findByText('Trip-Scoped Events');
await screen.findByText('User-Scoped Events');
});
it('FE-ADMIN-DEVNOTIF-002: four section titles render after data loads', async () => {
@@ -36,8 +72,7 @@ describe('DevNotificationsPanel', () => {
});
it('FE-ADMIN-DEVNOTIF-003: trip selector populated from API', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events');
await renderSettled();
const [tripSelect] = screen.getAllByRole('combobox');
const options = Array.from(tripSelect.querySelectorAll('option'));
const labels = options.map(o => o.textContent);
@@ -46,8 +81,7 @@ describe('DevNotificationsPanel', () => {
});
it('FE-ADMIN-DEVNOTIF-004: user selector populated from API', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('User-Scoped Events');
await renderSettled();
const selects = screen.getAllByRole('combobox');
// Second combobox is the user selector (first is trip selector)
const userSelect = selects[1];
@@ -66,8 +100,7 @@ describe('DevNotificationsPanel', () => {
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
await user.click(screen.getByText('Simple → Me').closest('button')!);
await waitFor(() => expect(capturedBody).toBeDefined());
expect(capturedBody).toMatchObject({
@@ -75,6 +108,8 @@ describe('DevNotificationsPanel', () => {
scope: 'user',
targetId: ADMIN_USER.id,
});
// The send settles inside this test, so its toast cannot land in the next one
await screen.findByText('Sent: simple-me');
});
it('FE-ADMIN-DEVNOTIF-006: success toast shown after fire', async () => {
@@ -84,30 +119,34 @@ describe('DevNotificationsPanel', () => {
),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
await user.click(screen.getByText('Simple → Me').closest('button')!);
expect(await screen.findByText('Sent: simple-me')).toBeInTheDocument();
});
it('FE-ADMIN-DEVNOTIF-007: all buttons disabled while a send is in-flight', async () => {
// The send is held open until the assertion ran, then released, so it settles in this test
let release!: () => void;
const gate = new Promise<void>(resolve => { release = resolve; });
server.use(
http.post('/api/admin/dev/test-notification', async () => {
await new Promise(() => {}); // never resolves — simulates in-flight
await gate;
return HttpResponse.json({ ok: true });
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
// The request handler never resolves, so sending stays true after the click settles
// The request handler is held, so sending stays true after the click settles
await user.click(screen.getByText('Simple → Me').closest('button')!);
await waitFor(() => {
const buttons = screen.getAllByRole('button');
buttons.forEach(btn => expect(btn).toBeDisabled());
});
release();
await screen.findByText('Sent: simple-me');
});
it('FE-ADMIN-DEVNOTIF-008: the server error field is what the toast shows', async () => {
@@ -117,8 +156,7 @@ describe('DevNotificationsPanel', () => {
),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
await user.click(screen.getByText('Simple → Me').closest('button')!);
expect(await screen.findByText('No channel configured')).toBeInTheDocument();
});
@@ -130,8 +168,7 @@ describe('DevNotificationsPanel', () => {
),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
await user.click(screen.getByText('Simple → Me').closest('button')!);
expect(await screen.findByText('Failed')).toBeInTheDocument();
});
@@ -145,8 +182,7 @@ describe('DevNotificationsPanel', () => {
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events');
await renderSettled();
const [tripSelect] = screen.getAllByRole('combobox');
const tokyoOption = Array.from(tripSelect.querySelectorAll('option')).find(
@@ -159,15 +195,19 @@ describe('DevNotificationsPanel', () => {
await waitFor(() => expect(capturedBody).toBeDefined());
expect(capturedBody!.targetId).toBe(tokyoId);
// The send settles inside this test, so its toast cannot land in the next one
await screen.findByText('Sent: booking_change');
});
it('FE-ADMIN-DEVNOTIF-010: Trip-Scoped section absent when no trips', async () => {
server.use(
http.get('/api/trips', () => HttpResponse.json({ trips: [] })),
);
const lookupsAnswered = trackRequests();
render(<><ToastContainer /><DevNotificationsPanel /></>);
// Wait for user data to confirm async effects have settled
await screen.findByText('User-Scoped Events');
await lookupsAnswered();
expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument();
});
@@ -180,8 +220,7 @@ describe('DevNotificationsPanel', () => {
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
await user.click(screen.getByText('Boolean → Me').closest('button')!);
await screen.findByText('Sent: boolean-me');
@@ -216,8 +255,7 @@ describe('DevNotificationsPanel', () => {
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events');
await renderSettled();
const [tripSelect] = screen.getAllByRole('combobox');
const tripId = Number((tripSelect as HTMLSelectElement).value);
@@ -247,8 +285,7 @@ describe('DevNotificationsPanel', () => {
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('User-Scoped Events');
await renderSettled();
const userSelect = screen.getAllByRole('combobox')[1] as HTMLSelectElement;
const aliceOption = Array.from(userSelect.querySelectorAll('option')).find(
@@ -278,9 +315,11 @@ describe('DevNotificationsPanel', () => {
it('FE-ADMIN-DEVNOTIF-014: the User-Scoped section is hidden when no users come back', async () => {
server.use(http.get('/api/admin/users', () => HttpResponse.json({ users: [] })));
const lookupsAnswered = trackRequests();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events');
await lookupsAnswered();
expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument();
});
@@ -288,18 +327,22 @@ describe('DevNotificationsPanel', () => {
server.use(
http.get('/api/trips', () => HttpResponse.error()),
http.get('/api/admin/users', () => HttpResponse.error()),
// A network error makes the API client probe /api/health before it rejects; the server
// is down here, so the probe fails too instead of going out to the real network
http.get('/api/health', () => HttpResponse.error()),
);
const lookupsAnswered = trackRequests([...LOOKUPS, '/api/health', '/api/health']);
render(<><ToastContainer /><DevNotificationsPanel /></>);
expect(await screen.findByText('Type Testing')).toBeInTheDocument();
await lookupsAnswered();
await waitFor(() => expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument());
expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument();
expect(screen.getByText('Admin-Scoped Events')).toBeInTheDocument();
});
it('FE-ADMIN-DEVNOTIF-016: a trigger takes its hover background from CSS, not inline styles', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
const btn = screen.getByText('Simple → Me').closest('button')!;
fireEvent.mouseEnter(btn);
@@ -1,32 +1,12 @@
// FE-PLANNER-DAYDETAIL-DF-001 to FE-PLANNER-DAYDETAIL-DF-002
// The day panel's heading with "date first in day headings" on (#2921).
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { buildAdmin, buildDay, buildTrip } from '../../../tests/helpers/factories';
import { server } from '../../../tests/helpers/msw/server';
import { dayDetailProps as props, resetDayDetailPanel } from '../../../tests/helpers/dayDetailPanel';
import { render, screen } from '../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { useAuthStore } from '../../store/authStore';
import { seedStore } from '../../../tests/helpers/store';
import { useSettingsStore } from '../../store/settingsStore';
import { useTripStore } from '../../store/tripStore';
import DayDetailPanel from './DayDetailPanel';
const day = buildDay({ id: 1, trip_id: 1, date: '2025-06-15', title: 'Day in Paris' });
const props = {
day,
days: [day],
places: [],
categories: [],
tripId: 1,
assignments: {},
reservations: [],
lat: null,
lng: null,
onClose: vi.fn(),
onAccommodationChange: vi.fn(),
};
function settings(dayDateFirst: boolean) {
seedStore(useSettingsStore, {
settings: { time_format: '24h', temperature_unit: 'celsius', day_date_first: dayDateFirst },
@@ -34,14 +14,7 @@ function settings(dayDateFirst: boolean) {
}
beforeEach(() => {
resetAllStores();
vi.clearAllMocks();
server.use(
http.get('/api/weather/detailed', () => HttpResponse.json({ error: true })),
http.get('/api/trips/1/accommodations', () => HttpResponse.json({ accommodations: [] }))
);
seedStore(useAuthStore, { user: buildAdmin(), isAuthenticated: true });
seedStore(useTripStore, { trip: buildTrip({ id: 1 }) });
resetDayDetailPanel();
});
describe('DayDetailPanel with the date first', () => {
@@ -5,43 +5,17 @@ import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
import { useAuthStore } from '../../store/authStore';
import { useTripStore } from '../../store/tripStore';
import { useSettingsStore } from '../../store/settingsStore';
import { usePermissionsStore } from '../../store/permissionsStore';
import { usePluginStore } from '../../store/pluginStore';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildUser, buildAdmin, buildTrip, buildDay, buildPlace, buildReservation } from '../../../tests/helpers/factories';
import { seedStore } from '../../../tests/helpers/store';
import { buildUser, buildAdmin, buildDay, buildPlace, buildReservation } from '../../../tests/helpers/factories';
import { dayDetailDay as day, dayDetailProps as defaultProps, resetDayDetailPanel } from '../../../tests/helpers/dayDetailPanel';
import DayDetailPanel from './DayDetailPanel';
import { isBlurred } from '../../../tests/helpers/bookingCodeBlur';
const day = buildDay({ id: 1, trip_id: 1, date: '2025-06-15', title: 'Day in Paris' });
const defaultProps = {
day,
days: [day],
places: [],
categories: [],
tripId: 1,
assignments: {},
reservations: [],
lat: null,
lng: null,
onClose: vi.fn(),
onAccommodationChange: vi.fn(),
};
beforeEach(() => {
resetAllStores();
vi.clearAllMocks();
server.use(
http.get('/api/weather/detailed', () => HttpResponse.json({ error: true })),
http.get('/api/trips/1/accommodations', () => HttpResponse.json({ accommodations: [] })),
);
seedStore(useAuthStore, { user: buildAdmin(), isAuthenticated: true });
seedStore(useTripStore, { trip: buildTrip({ id: 1 }) });
seedStore(useSettingsStore, {
settings: { time_format: '24h', temperature_unit: 'celsius', blur_booking_codes: false },
});
resetDayDetailPanel({ time_format: '24h', temperature_unit: 'celsius', blur_booking_codes: false });
});
/** The stay picker filters by category through a pill that opens its list; this picks one entry of it. */
@@ -147,13 +121,23 @@ describe('DayDetailPanel', () => {
});
it('FE-PLANNER-DAYDETAIL-009: weather loading state shown briefly', async () => {
// The forecast is held until the spinner was seen, then released, so the request
// does not stay open past this test.
let release!: () => void;
const gate = new Promise<void>((resolve) => { release = resolve; });
server.use(
http.get('/api/weather/detailed', () => new Promise(() => {})), // never resolves
http.get('/api/weather/detailed', async () => {
await gate;
return HttpResponse.json({ error: true });
}),
);
render(<DayDetailPanel {...defaultProps} lat={48.8566} lng={2.3522} />);
// The spinner announces itself as a loading status
const spinner = await screen.findByRole('status', { name: 'Loading...' });
expect(spinner.querySelector('.animate-spin')).not.toBeNull();
release();
expect(await screen.findByText(/No weather/i)).toBeInTheDocument();
});
it('FE-PLANNER-DAYDETAIL-101: a late forecast for the previous day never replaces the one for the current day', async () => {
@@ -1606,14 +1590,14 @@ describe('DayDetailPanel remaining branches', () => {
const user = userEvent.setup();
const onAccommodationChange = vi.fn();
let updateBody: Record<string, unknown> | null = null;
let listCalls = 0;
// The reload after the save reads the new name; keyed on the save, not on a
// count of reads, so a stray read before it cannot rename the stay early.
server.use(
http.get('/api/trips/1/accommodations', () => {
listCalls += 1;
return HttpResponse.json({
accommodations: [hotel(listCalls > 1 ? { place_name: 'Reloaded Hotel' } : {})],
});
}),
http.get('/api/trips/1/accommodations', () =>
HttpResponse.json({
accommodations: [hotel(updateBody ? { place_name: 'Reloaded Hotel' } : {})],
}),
),
http.put('/api/trips/1/accommodations/1', async ({ request }) => {
updateBody = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ accommodation: hotel() });
@@ -1874,25 +1858,40 @@ describe('DayDetailPanel remaining branches, part two', () => {
expect(await screen.findByText('15h 20m')).toBeInTheDocument();
});
it('FE-W5DDP-021: a collapsed untitled day falls back to its position, or to ? when it has none', () => {
it('FE-W5DDP-021: a collapsed untitled day falls back to its position, or to ? when it has none', async () => {
// Each mount reads the stays; wait for that read to be answered, so it cannot
// reach the handler of the test that runs next.
let staysRead = 0;
server.use(
http.get('/api/trips/1/accommodations', () => {
staysRead += 1;
return HttpResponse.json({ accommodations: [] });
}),
);
const bare = buildDay({ id: 2, trip_id: 1, date: null, title: null });
const { unmount } = render(<DayDetailPanel {...defaultProps} day={bare} days={[defaultProps.day, bare]} collapsed />);
expect(screen.getByText('Day 2')).toBeInTheDocument();
await waitFor(() => expect(staysRead).toBe(1));
unmount();
render(<DayDetailPanel {...defaultProps} day={bare} days={[]} collapsed />);
expect(screen.getByText('Day ?')).toBeInTheDocument();
await waitFor(() => expect(staysRead).toBe(2));
});
it('FE-W5DDP-020: an empty reload after the edit-save clears the accommodation', async () => {
const user = userEvent.setup();
let listCalls = 0;
// The list empties once the edit is saved, not on a count of reads, so a stray
// read before the save cannot empty it early.
let saved = false;
server.use(
http.get('/api/trips/1/accommodations', () => {
listCalls += 1;
return listCalls === 1 ? HttpResponse.json({ accommodations: [hotel()] }) : HttpResponse.json({});
http.get('/api/trips/1/accommodations', () =>
saved ? HttpResponse.json({}) : HttpResponse.json({ accommodations: [hotel()] }),
),
http.put('/api/trips/1/accommodations/1', () => {
saved = true;
return HttpResponse.json({ accommodation: hotel() });
}),
http.put('/api/trips/1/accommodations/1', () => HttpResponse.json({ accommodation: hotel() })),
);
render(<DayDetailPanel {...defaultProps} places={[buildPlace({ id: 5, name: 'Grand Hotel' })]} />);
+4 -2
View File
@@ -1535,8 +1535,10 @@ describe('AdminPage', () => {
const matrixCard = matrixHeading.closest<HTMLElement>('section');
// The matrix switch is named after its event and channel; the card's first
// buttons belong to the webhook and ntfy targets above the matrix.
fireEvent.click(within(matrixCard!).getByRole('button', { name: /, email$/i }));
// buttons belong to the webhook and ntfy targets above the matrix. The card's
// heading renders before the matrix fetch lands (a loading row stands in until
// then), so wait for the switch itself.
fireEvent.click(await within(matrixCard!).findByRole('button', { name: /, email$/i }));
await waitFor(() => {
expect(prefUpdateCalled).toBe(true);
+6 -1
View File
@@ -276,7 +276,10 @@ describe('AtlasPage wiring', () => {
fireEvent.click(screen.getByText('atlas.unmark'));
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenLastCalledWith(null));
// The cancel above already closed with null, so wait for the unmark's own close:
// it comes only after the region delete and the country check have both answered.
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenCalledTimes(2));
expect(atlas.setConfirmAction).toHaveBeenLastCalledWith(null);
expect(atlas.visitedRegions).toEqual({});
const data = atlas.data as AtlasData;
expect(data.countries.map((c) => c.code)).toEqual(['FR']);
@@ -379,6 +382,8 @@ describe('AtlasPage wiring', () => {
fireEvent.click(screen.getByText('atlas.addToBucket'));
await waitFor(() => expect(body).toMatchObject({ name: 'Bretagne', country_code: 'FR', target_date: null }));
// Let the post answer and the popup close here, not in the next test.
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenLastCalledWith(null));
});
it('FE-PAGE-ATLASW-018b: a country already wishlisted for that date is not posted again (#1898)', async () => {
@@ -5,6 +5,7 @@ import React from 'react';
import { MemoryRouter } from 'react-router';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { buildAppConfig } from '../../../tests/helpers/factories';
import { locationAt, pageUrl } from '../../../tests/helpers/location';
import { server } from '../../../tests/helpers/msw/server';
import { act, renderHook, waitFor } from '../../../tests/helpers/render';
import { resetAllStores } from '../../../tests/helpers/store';
@@ -54,7 +55,7 @@ beforeEach(() => {
Object.defineProperty(window, 'location', {
configurable: true,
writable: true,
value: { ...realLocation, pathname: '/login', href: 'http://localhost/login', search: '' },
value: locationAt('/login'),
});
});
@@ -78,7 +79,7 @@ describe('useLogin in the native app', () => {
);
const { result } = renderLogin();
await waitFor(() => expect(result.current.appConfig).not.toBeNull());
expect(window.location.href).toBe('http://localhost/login');
expect(window.location.href).toBe(pageUrl('/login'));
expect(result.current.oidcOnly).toBe(true);
});
+17 -10
View File
@@ -7,6 +7,7 @@ import { http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores } from '../../../tests/helpers/store';
import { buildAppConfig } from '../../../tests/helpers/factories';
import { locationAt, pageUrl } from '../../../tests/helpers/location';
import { markSignedOut, clearSignedOut, wasSignedOut } from '../../utils/signedOut';
import { TranslationProvider } from '../../i18n/TranslationContext';
import { useAuthStore, type LoginResult } from '../../store/authStore';
@@ -54,7 +55,7 @@ function setSearch(search: string) {
Object.defineProperty(window, 'location', {
configurable: true,
writable: true,
value: { ...realLocation, pathname: '/login', href: 'http://localhost/login', search },
value: locationAt(`/login${search}`),
});
}
@@ -196,7 +197,7 @@ describe('useLogin — app config probe', () => {
await ready(result);
expect(result.current.noRedirect).toBe(true);
expect(window.location.href).toBe('http://localhost/login');
expect(window.location.href).toBe(pageUrl('/login'));
});
it('FE-LOGIN-HOOK-009: never auto-redirects on a cached config', async () => {
@@ -210,7 +211,7 @@ describe('useLogin — app config probe', () => {
await ready(result);
expect(result.current.oidcOnly).toBe(true);
expect(window.location.href).toBe('http://localhost/login');
expect(window.location.href).toBe(pageUrl('/login'));
});
});
@@ -1183,13 +1184,13 @@ describe('useLogin — the wait before the sign-in is known (#1167)', () => {
await waitFor(() => expect(result.current.redirectScreen).toBe(false));
expect(result.current.configWait).toBe(false);
expect(result.current.oidcOnly).toBe(true);
expect(window.location.href).toBe('http://localhost/login');
expect(window.location.href).toBe(pageUrl('/login'));
});
it('FE-LOGIN-HOOK-208: a redirect that stalls offers the way on by hand after eight seconds', () => {
it('FE-LOGIN-HOOK-208: a redirect that stalls offers the way on by hand after eight seconds', async () => {
vi.useFakeTimers();
localStorage.setItem(CONFIG_CACHE_KEY, JSON.stringify(oidcOnlyConfig()));
heldConfig(oidcOnlyConfig());
const release = heldConfig(oidcOnlyConfig());
const { result } = renderLogin();
expect(result.current.redirectScreen).toBe(true);
@@ -1197,6 +1198,12 @@ describe('useLogin — the wait before the sign-in is known (#1167)', () => {
expect(result.current.idpSlow).toBe(false);
act(() => { vi.advanceTimersByTime(1); });
expect(result.current.idpSlow).toBe(true);
// The probe answers in the end and the redirect goes ahead, here and not in
// the next test.
vi.useRealTimers();
release();
await waitFor(() => expect(window.location.href).toBe('/api/auth/oidc/login?remember=1'));
});
it('FE-LOGIN-HOOK-209: a failed sign-in at the IdP shows the OIDC-only screen and its error, without going back', async () => {
@@ -1209,7 +1216,7 @@ describe('useLogin — the wait before the sign-in is known (#1167)', () => {
expect(result.current.configWait).toBe(false);
expect(result.current.redirectScreen).toBe(false);
expect(result.current.error).not.toBe('');
expect(window.location.href).toBe('http://localhost/login');
expect(window.location.href).toBe(pageUrl('/login?oidc_error=token_failed'));
});
it('FE-LOGIN-HOOK-215: with the auto redirect turned off the page stays, with its SSO button (#2925)', async () => {
@@ -1222,7 +1229,7 @@ describe('useLogin — the wait before the sign-in is known (#1167)', () => {
expect(result.current.oidcOnly).toBe(true);
expect(result.current.redirectScreen).toBe(false);
expect(result.current.configWait).toBe(false);
expect(window.location.href).toBe('http://localhost/login');
expect(window.location.href).toBe(pageUrl('/login'));
});
it('FE-LOGIN-HOOK-216: a cached config with the auto redirect off announces no redirect while the probe is out', async () => {
@@ -1237,7 +1244,7 @@ describe('useLogin — the wait before the sign-in is known (#1167)', () => {
release();
await ready(result);
expect(result.current.redirectScreen).toBe(false);
expect(window.location.href).toBe('http://localhost/login');
expect(window.location.href).toBe(pageUrl('/login'));
});
it('FE-LOGIN-HOOK-217: a server from before the switch, with no field, keeps the redirect', async () => {
@@ -1259,6 +1266,6 @@ describe('useLogin — the wait before the sign-in is known (#1167)', () => {
release();
await ready(result);
expect(window.location.href).toBe('http://localhost/login');
expect(window.location.href).toBe(pageUrl('/login'));
});
});
@@ -2,6 +2,7 @@
import React from 'react';
import { MemoryRouter } from 'react-router';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { locationAt } from '../../../tests/helpers/location';
import { act, renderHook, waitFor } from '../../../tests/helpers/render';
import { resetAllStores } from '../../../tests/helpers/store';
import { rememberHandoffReturn, requestHandoffCode, signInWithPasskey } from '../../native/browserSignIn';
@@ -28,7 +29,7 @@ function setSearch(search: string) {
Object.defineProperty(window, 'location', {
configurable: true,
writable: true,
value: { ...realLocation, search, href: 'http://localhost/native-handoff' + search, replace: vi.fn() },
value: locationAt(`/native-handoff${search}`, { replace: vi.fn() }),
});
}
+7
View File
@@ -160,6 +160,13 @@ describe('helpStore: search', () => {
})
describe('helpStore: doc index', () => {
// Loading the index has no debounce, so these tests await the response directly.
// msw no longer runs its own timers outside fake ones, and a successful mocked
// response only arrives once a timer fires, so these tests run on real timers.
beforeEach(() => {
vi.useRealTimers()
})
it('loads the table of contents once and resolves titles from it', async () => {
let calls = 0
server.use(
+9 -7
View File
@@ -1,4 +1,5 @@
import { isChunkLoadError, reloadOnceForChunk, clearChunkReloadMarker, reloadFresh, importChunk, FRESH_LOAD_PARAM } from './chunkReload';
import { locationAt, pageUrl } from '../../tests/helpers/location';
const net = vi.hoisted(() => ({
probeNow: vi.fn(async () => 'online' as 'online' | 'offline' | 'proxy-wall'),
@@ -38,11 +39,11 @@ describe('isChunkLoadError', () => {
* A recovery reload is a location.replace onto a fresh URL (reloadFresh), so the
* stub records the replace. `plain` is the location.reload() it must not use.
*/
function stubLocation(href = 'http://localhost/trips/4?tab=plan#day-2') {
function stubLocation(path = '/trips/4?tab=plan#day-2', overrides: Partial<Location> = {}) {
const reload = vi.fn();
const plain = vi.fn();
Object.defineProperty(window, 'location', {
value: { ...window.location, href, replace: reload, reload: plain },
value: locationAt(path, { replace: reload, reload: plain, ...overrides }),
writable: true,
});
return { reload, plain };
@@ -56,7 +57,8 @@ describe('reloadFresh', () => {
expect(plain).not.toHaveBeenCalled();
expect(reload).toHaveBeenCalledTimes(1);
const target = new URL(reload.mock.calls[0][0] as string);
// Path, query and hash stay, so the app comes back where it was.
// Origin, path, query and hash stay, so the app comes back where it was.
expect(target.origin).toBe(new URL(pageUrl('/')).origin);
expect(target.pathname).toBe('/trips/4');
expect(target.searchParams.get('tab')).toBe('plan');
expect(target.hash).toBe('#day-2');
@@ -64,7 +66,7 @@ describe('reloadFresh', () => {
});
it('FE-UTIL-CHUNK-016: two reloads never share a URL', () => {
const { reload } = stubLocation('http://localhost/dashboard');
const { reload } = stubLocation('/dashboard');
const now = vi.spyOn(Date, 'now').mockReturnValue(1790358416100);
reloadFresh();
now.mockReturnValue(1790358416101);
@@ -73,7 +75,7 @@ describe('reloadFresh', () => {
});
it('FE-UTIL-CHUNK-017: falls back to a plain reload when the URL cannot be built', () => {
const { reload, plain } = stubLocation('not a url');
const { reload, plain } = stubLocation('/', { href: 'not a url' });
reloadFresh();
expect(reload).not.toHaveBeenCalled();
expect(plain).toHaveBeenCalledTimes(1);
@@ -145,7 +147,7 @@ describe('reloadOntoCurrentBuild', () => {
const deleted: string[] = [];
Object.defineProperty(globalThis, 'caches', {
value: {
keys: vi.fn(async () => ['workbox-precache-v2-http://localhost/', 'map-tiles']),
keys: vi.fn(async () => [`workbox-precache-v2-${pageUrl('/')}`, 'map-tiles']),
delete: vi.fn(async (name: string) => { deleted.push(name); return true; }),
},
configurable: true,
@@ -191,7 +193,7 @@ describe('reloadOntoCurrentBuild', () => {
// Not before the shell is gone: the reload would come back to the same error.
expect(reload).not.toHaveBeenCalled();
await vi.waitFor(() => expect(reload).toHaveBeenCalledTimes(1));
expect(deleted).toEqual(['workbox-precache-v2-http://localhost/']);
expect(deleted).toEqual([`workbox-precache-v2-${pageUrl('/')}`]);
expect(registration.unregister).toHaveBeenCalledTimes(1);
});
+2 -1
View File
@@ -1,4 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { locationAt } from '../../tests/helpers/location'
/*
* reconcileAppVersion notes the worker that served the page when its module
@@ -85,7 +86,7 @@ beforeEach(() => {
plainReload = vi.fn()
Object.defineProperty(window, 'location', {
writable: true,
value: { ...window.location, href: 'http://localhost/dashboard', replace: reload, reload: plainReload },
value: locationAt('/dashboard', { replace: reload, reload: plainReload }),
})
})
+44
View File
@@ -0,0 +1,44 @@
import { http, HttpResponse } from 'msw';
import { vi } from 'vitest';
import { useAuthStore } from '../../src/store/authStore';
import { useSettingsStore } from '../../src/store/settingsStore';
import { useTripStore } from '../../src/store/tripStore';
import type { Settings } from '../../src/types';
import { buildAdmin, buildDay, buildTrip } from './factories';
import { server } from './msw/server';
import { resetAllStores, seedStore } from './store';
/** The day the day panel suites open. */
export const dayDetailDay = buildDay({ id: 1, trip_id: 1, date: '2025-06-15', title: 'Day in Paris' });
/** The panel's props for that day, with nothing planned on it. */
export const dayDetailProps = {
day: dayDetailDay,
days: [dayDetailDay],
places: [],
categories: [],
tripId: 1,
assignments: {},
reservations: [],
lat: null,
lng: null,
onClose: vi.fn(),
onAccommodationChange: vi.fn(),
};
/**
* Fresh stores for each day panel test: an admin on trip 1, the forecast and the stays
* answering empty, and the given settings when the suite wants them before rendering.
*/
export function resetDayDetailPanel(settings?: Partial<Settings>): void {
resetAllStores();
vi.clearAllMocks();
server.use(
http.get('/api/weather/detailed', () => HttpResponse.json({ error: true })),
http.get('/api/trips/1/accommodations', () => HttpResponse.json({ accommodations: [] }))
);
seedStore(useAuthStore, { user: buildAdmin(), isAuthenticated: true });
seedStore(useTripStore, { trip: buildTrip({ id: 1 }) });
if (settings) seedStore(useSettingsStore, { settings });
}
+35
View File
@@ -0,0 +1,35 @@
// The page's own location, taken when this module loads, before any test
// replaces window.location with a stand-in.
const pageLocation = window.location;
const pageOrigin = new URL(document.baseURI).origin;
/** `path` as an absolute URL on the page's own origin, for asserting on location.href. */
export function pageUrl(path: string): string {
return new URL(path, pageOrigin).href;
}
/**
* A stand-in for window.location that shows `path` on the page's own origin.
*
* Requests have to stay on one origin for the HTTP mocks to answer them: msw
* resolves its relative handlers, and its fetch interceptor a relative URL,
* against location.href, while jsdom's XHR resolves against the document. A
* stand-in on another origin (`http://localhost/` while the page runs on
* `http://localhost:3000`) sends every request past its handler.
*/
export function locationAt(path: string, overrides: Partial<Location> = {}): Location {
const url = new URL(path, pageOrigin);
return {
...pageLocation,
href: url.href,
origin: url.origin,
protocol: url.protocol,
host: url.host,
hostname: url.hostname,
port: url.port,
pathname: url.pathname,
search: url.search,
hash: url.hash,
...overrides,
};
}
+27 -19
View File
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { http, HttpResponse } from 'msw';
import { server } from '../../helpers/msw/server';
import { buildUser } from '../../helpers/factories';
import { locationAt, pageUrl } from '../../helpers/location';
// The global setup.ts mocks websocket with getSocketId returning null.
// We need to be able to control what getSocketId returns per-test.
@@ -59,7 +60,7 @@ describe('API client interceptors', () => {
// Reset window.location to a neutral path
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'http://localhost/', pathname: '/', search: '', hash: '' },
value: locationAt('/'),
});
});
@@ -97,7 +98,7 @@ describe('API client interceptors', () => {
it('FE-API-003: 401 with AUTH_REQUIRED → redirects to /login with redirect param', async () => {
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'http://localhost/', pathname: '/dashboard', search: '', hash: '' },
value: locationAt('/dashboard'),
});
server.use(
@@ -118,7 +119,7 @@ describe('API client interceptors', () => {
it('FE-API-003b: 401 without AUTH_REQUIRED code does not redirect', async () => {
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'http://localhost/dashboard', pathname: '/dashboard', search: '' },
value: locationAt('/dashboard'),
});
const originalHref = window.location.href;
@@ -141,7 +142,7 @@ describe('API client interceptors', () => {
it('FE-API-003c: 401 on /login page does not redirect', async () => {
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'http://localhost/login', pathname: '/login', search: '' },
value: locationAt('/login'),
});
server.use(
@@ -157,13 +158,13 @@ describe('API client interceptors', () => {
}
// href should NOT have been changed to /login?redirect=...
expect(window.location.href).toBe('http://localhost/login');
expect(window.location.href).toBe(pageUrl('/login'));
});
it('FE-API-004: 403 with MFA_REQUIRED → redirects to /settings?mfa=required', async () => {
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'http://localhost/', pathname: '/dashboard', search: '' },
value: locationAt('/dashboard'),
});
server.use(
@@ -184,7 +185,7 @@ describe('API client interceptors', () => {
it('FE-API-004b: 403 with MFA_REQUIRED on /settings page does not redirect', async () => {
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'http://localhost/settings', pathname: '/settings', search: '' },
value: locationAt('/settings'),
});
server.use(
@@ -200,7 +201,7 @@ describe('API client interceptors', () => {
}
// Should NOT redirect when already on /settings
expect(window.location.href).toBe('http://localhost/settings');
expect(window.location.href).toBe(pageUrl('/settings'));
});
it('FE-API-005: successful API call returns response data', async () => {
@@ -253,7 +254,7 @@ describe('API client interceptors', () => {
it('FE-API-008: 401 AUTH_REQUIRED on /register path does not redirect', async () => {
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'http://localhost/register', pathname: '/register', search: '' },
value: locationAt('/register'),
});
server.use(
@@ -264,13 +265,13 @@ describe('API client interceptors', () => {
try { await authApi.me(); } catch { /* expected */ }
expect(window.location.href).toBe('http://localhost/register');
expect(window.location.href).toBe(pageUrl('/register'));
});
it('FE-API-009: 401 AUTH_REQUIRED on /shared/:token path does not redirect', async () => {
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'http://localhost/shared/abc123', pathname: '/shared/abc123', search: '' },
value: locationAt('/shared/abc123'),
});
server.use(
@@ -281,13 +282,13 @@ describe('API client interceptors', () => {
try { await authApi.me(); } catch { /* expected */ }
expect(window.location.href).toBe('http://localhost/shared/abc123');
expect(window.location.href).toBe(pageUrl('/shared/abc123'));
});
it('FE-API-010: 401 AUTH_REQUIRED still rejects the promise even when redirect fires', async () => {
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'http://localhost/dashboard', pathname: '/dashboard', search: '' },
value: locationAt('/dashboard'),
});
server.use(
@@ -304,7 +305,7 @@ describe('API client interceptors', () => {
it('FE-API-011: 403 without MFA_REQUIRED code does not redirect', async () => {
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'http://localhost/dashboard', pathname: '/dashboard', search: '' },
value: locationAt('/dashboard'),
});
server.use(
@@ -315,13 +316,13 @@ describe('API client interceptors', () => {
try { await authApi.me(); } catch { /* expected */ }
expect(window.location.href).toBe('http://localhost/dashboard');
expect(window.location.href).toBe(pageUrl('/dashboard'));
});
it('FE-API-012: 403 MFA_REQUIRED still rejects the promise after redirect fires', async () => {
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'http://localhost/dashboard', pathname: '/dashboard', search: '' },
value: locationAt('/dashboard'),
});
server.use(
@@ -962,11 +963,13 @@ describe('mapsApi', () => {
it('FE-MAPS-004: mapsApi.autocomplete rejects when AbortSignal is aborted', async () => {
const controller = new AbortController();
let release!: () => void;
const gate = new Promise<void>(resolve => { release = resolve; });
server.use(
http.post('/api/maps/autocomplete', async () => {
// Never resolves — request will be aborted
await new Promise(() => {});
// Held until the request has been aborted
await gate;
return HttpResponse.json({ suggestions: [] });
})
);
@@ -974,6 +977,11 @@ describe('mapsApi', () => {
const promise = mapsApi.autocomplete('Paris', undefined, undefined, controller.signal);
controller.abort();
await expect(promise).rejects.toThrow();
try {
await expect(promise).rejects.toThrow();
} finally {
// Let the held handler finish here, not in whatever runs after this test.
release();
}
});
});
+6 -3
View File
@@ -26,10 +26,13 @@ vi.mock('../src/api/websocket', () => ({
// lets it through, so the runner really talks to frankfurter or a tile server and settles
// a promise after the test environment is gone (see handlers/external.ts). Those fail now.
// An unhandled same-origin call stays a warning: that is a missing handler, not egress.
// Only HTTP frames are judged, as before msw 3 reported every network frame here.
beforeAll(() => server.listen({
onUnhandledRequest: (request, print) => {
if (new URL(request.url).origin === location.origin) print.warning();
else print.error();
onUnhandledFrame: ({ frame, defaults }) => {
if (frame.protocol !== 'http') return;
const { request } = frame.data as { request: Request };
if (new URL(request.url).origin === location.origin) defaults.warn();
else defaults.error();
},
}));
afterEach(() => {
@@ -442,6 +442,9 @@ describe('MSettingsPlugins', () => {
expect(frame).toHaveAttribute('data-plugin', 'p1');
expect(frame).toHaveAttribute('data-path', 'settings.html');
expect(frame).toHaveAttribute('data-title', 'Weather Pro');
// The framed card renders at once, the declared-field form only once its
// settings request answered; wait for that form before counting the cards.
await screen.findByPlaceholderText('https://api.example');
// Declared-field form and framed surface are two separate cards
expect(screen.getAllByText('Weather Pro')).toHaveLength(2);
});
@@ -266,7 +266,9 @@ describe('MCollabChat', () => {
expect(send).toBeEnabled()
fireEvent.click(send)
expect(await screen.findByText('Landed safely')).toBeInTheDocument()
// React mirrors the draft into the textarea's text, so the composer itself
// matches the trimmed text; wait for the appended bubble, not the draft.
expect(await screen.findByText('Landed safely', { ignore: 'script, style, textarea' })).toBeInTheDocument()
expect(sentBodies).toEqual([{ text: 'Landed safely' }])
expect(input).toHaveValue('')
})
@@ -1,21 +1,39 @@
// FE-MOB-MVACINV-001 to FE-MOB-MVACINV-010
import React from 'react';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { describe, it, expect, beforeEach, afterEach, vi, type MockInstance } from 'vitest';
import { http, HttpResponse } from 'msw';
import { render, screen, fireEvent, waitFor, within } from '../../../helpers/render';
import { render, screen, fireEvent, waitFor, within, act } from '../../../helpers/render';
import { server } from '../../../helpers/msw/server';
import { resetAllStores } from '../../../helpers/store';
import { useVacayStore } from '../../../../src/store/vacayStore';
import apiClient from '../../../../src/api/client';
import MVacayInviteSheet from '../../../../src/mobile/screens/vacay/MVacayInviteSheet';
const toasts: { type: string; message: string }[] = [];
const USERS_ENDPOINT = '/addons/vacay/available-users';
let getSpy: MockInstance<typeof apiClient.get>;
function availableUsers(users: { id: number; username: string; color: string | null }[]) {
server.use(http.get('/api/addons/vacay/available-users', () => HttpResponse.json({ users })));
}
/**
* Waits until the sheet has asked for the invitable users `lookups` times and
* every answer has come back and been applied. The answer is not on screen when
* it changes nothing (an empty list, the same list on a reload), and a lookup
* still out when the test ends would land in the next one.
*/
async function usersSettled(lookups: number) {
const calls = () => getSpy.mock.calls.flatMap(([url], i) => (url === USERS_ENDPOINT ? [getSpy.mock.results[i].value] : []));
await waitFor(() => expect(calls()).toHaveLength(lookups));
await act(async () => {
await Promise.allSettled(calls());
});
}
beforeEach(() => {
resetAllStores();
getSpy = vi.spyOn(apiClient, 'get');
toasts.length = 0;
window.__addToast = ((message: string, type?: string) => {
toasts.push({ type: type ?? 'info', message });
@@ -28,6 +46,7 @@ beforeEach(() => {
});
afterEach(() => {
getSpy.mockRestore();
delete window.__addToast;
});
@@ -54,6 +73,7 @@ describe('MVacayInviteSheet', () => {
it('FE-MOB-MVACINV-003: falls back to the empty state when the lookup fails', async () => {
server.use(http.get('/api/addons/vacay/available-users', () => HttpResponse.json({ error: 'nope' }, { status: 500 })));
renderSheet();
await usersSettled(1);
expect(await screen.findByText('No users available')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Select user' })).not.toBeInTheDocument();
@@ -74,7 +94,9 @@ describe('MVacayInviteSheet', () => {
const send = await screen.findByRole('button', { name: 'Send Invite' });
expect(send).toBeDisabled();
fireEvent.click(screen.getByRole('button', { name: 'Select user' }));
// The picker shows up once the users are in; nobody is picked yet.
fireEvent.click(await screen.findByRole('button', { name: 'Select user' }));
expect(screen.getByRole('button', { name: 'Send Invite' })).toBeDisabled();
fireEvent.click(screen.getByRole('button', { name: 'bob' }));
expect(screen.getByRole('button', { name: 'Send Invite' })).toBeEnabled();
});
@@ -122,6 +144,7 @@ describe('MVacayInviteSheet', () => {
fireEvent.click(within(row).getByRole('button', { name: 'Cancel' }));
expect(cancelInvite).toHaveBeenCalledWith(9);
await usersSettled(1);
});
it('FE-MOB-MVACINV-009: the close icon and the cancel button both dismiss the sheet', async () => {
@@ -131,6 +154,7 @@ describe('MVacayInviteSheet', () => {
const dialog = screen.getByRole('dialog', { name: 'Invite User' });
fireEvent.click(within(dialog).getAllByRole('button', { name: 'Cancel' })[0]);
expect(onClose).toHaveBeenCalledTimes(2);
await usersSettled(1);
});
it('FE-MOB-MVACINV-010: reopening resets the previous selection', async () => {
@@ -141,6 +165,7 @@ describe('MVacayInviteSheet', () => {
rerender(<MVacayInviteSheet open={false} onClose={() => {}} />);
rerender(<MVacayInviteSheet open onClose={() => {}} />);
await usersSettled(2);
expect(await screen.findByRole('button', { name: 'Select user' })).toBeInTheDocument();
});
+10 -7
View File
@@ -5,10 +5,13 @@
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { locationAt, pageUrl } from '../../helpers/location';
const SOURCE = readFileSync(resolve(process.cwd(), 'public/shell-guard.js'), 'utf8');
const ENTRY = '/assets/index-BZcJ9-lk.js';
const MARKER = 'trek:shell-reload';
// Workbox names its precache after the scope the worker was registered for.
const PRECACHE = `workbox-precache-v2-${pageUrl('/')}`;
type Listener = [string, EventListenerOrEventListenerObject, boolean | AddEventListenerOptions | undefined];
let listeners: Listener[] = [];
@@ -51,21 +54,21 @@ interface Env {
deleted: string[];
}
/** A page a service worker served, unless `controlled` is false. */
function install(href = 'http://localhost/trips/4?tab=plan#day-2', controlled = true): Env {
/** The page at `path`, one a service worker served unless `controlled` is false. */
function install(path = '/trips/4?tab=plan#day-2', controlled = true): Env {
const replace = vi.fn();
Object.defineProperty(window, 'location', { value: { ...window.location, href, replace }, writable: true, configurable: true });
Object.defineProperty(window, 'location', { value: locationAt(path, { replace }), writable: true, configurable: true });
const fetch = vi.fn(async () => healthAnswer(true, 'application/json; charset=utf-8'));
vi.stubGlobal('fetch', fetch);
const unregister = vi.fn(async () => true);
Object.defineProperty(navigator, 'serviceWorker', {
value: { controller: controlled ? { scriptURL: 'http://localhost/sw.js' } : null, getRegistration: vi.fn(async () => ({ unregister })) },
value: { controller: controlled ? { scriptURL: pageUrl('/sw.js') } : null, getRegistration: vi.fn(async () => ({ unregister })) },
configurable: true,
});
const deleted: string[] = [];
Object.defineProperty(globalThis, 'caches', {
value: {
keys: vi.fn(async () => ['workbox-precache-v2-http://localhost/', 'map-tiles', 'gl-map-offline', 'user-uploads']),
keys: vi.fn(async () => [PRECACHE, 'map-tiles', 'gl-map-offline', 'user-uploads']),
delete: vi.fn(async (name: string) => { deleted.push(name); return true; }),
},
configurable: true,
@@ -117,7 +120,7 @@ describe('shell-guard.js', () => {
expect(env.fetch).toHaveBeenCalledWith('/api/health', expect.objectContaining({ cache: 'no-store', redirect: 'manual' }));
// Only the precache: offline map regions and cached uploads were downloaded on purpose.
expect(env.deleted).toEqual(['workbox-precache-v2-http://localhost/']);
expect(env.deleted).toEqual([PRECACHE]);
expect(env.unregister).toHaveBeenCalledTimes(1);
const target = new URL(env.replace.mock.calls[0][0] as string);
expect(target.pathname + target.hash).toBe('/trips/4#day-2');
@@ -191,7 +194,7 @@ describe('shell-guard.js', () => {
it('FE-SHELLGUARD-011: a page that came from the network is reloaded afresh and its worker kept', async () => {
// Nothing the worker keeps answered this load, so throwing it away would only
// cost the offline shell.
const env = install('http://localhost/dashboard', false);
const env = install('/dashboard', false);
runGuard();
fail(moduleScript(ENTRY));
await vi.waitFor(() => expect(env.replace).toHaveBeenCalledTimes(1));