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
+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));