mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 15:23:29 +00:00
test: add a browser Vitest project for interactive components
Run *.browser.test.tsx in headless Chromium through the Playwright provider. The shared helper in tests/browser/ mounts the app's own providers, stubs only the fetch boundary, and shims next/navigation onto the page's real location and history.
This commit is contained in:
1 parent
3eb5aa9364
commit
3d1692204b
9 files changed
+736
-32
No files matched your search
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* The network boundary for browser tests.
|
||||
*
|
||||
* Components talk to the server through `@/lib/api/api-fetch`, which calls
|
||||
* the global `fetch`. Replacing `fetch` and nothing else keeps everything
|
||||
* above it real: the envelope unwrapping, the idempotency header, TanStack
|
||||
* Query's caching and retries, the component's own pending and error states.
|
||||
* Never mock `@tanstack/react-query` or the API wrapper in this project; a
|
||||
* test that does asserts its own stand-in.
|
||||
*
|
||||
* Every request is recorded with its parsed JSON body, so a form test asserts
|
||||
* the payload the server would receive. A route can answer later than the
|
||||
* request (`deferred`), which is how a test holds a form in its pending
|
||||
* state. A request no route matches fails with a 404 envelope and is recorded
|
||||
* too, so an unexpected call is visible rather than hanging.
|
||||
*
|
||||
* `setup.ts` restores the real `fetch` after every test.
|
||||
*/
|
||||
export interface RecordedRequest {
|
||||
method: string;
|
||||
/** Path and query, without the origin. */
|
||||
path: string;
|
||||
headers: Headers;
|
||||
/** The parsed JSON body, or the raw text when it is not JSON. */
|
||||
body: unknown;
|
||||
}
|
||||
|
||||
export interface StubResponse {
|
||||
status?: number;
|
||||
/** The envelope's `data`. Ignored when `error` is set. */
|
||||
data?: unknown;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
type Responder = (
|
||||
request: RecordedRequest,
|
||||
) => StubResponse | Promise<StubResponse>;
|
||||
|
||||
interface Route {
|
||||
method: string;
|
||||
path: string | RegExp;
|
||||
respond: Responder;
|
||||
}
|
||||
|
||||
export interface FetchStub {
|
||||
/** Answer `method path` (exact path, or a pattern) with `response`. */
|
||||
on(
|
||||
method: string,
|
||||
path: string | RegExp,
|
||||
response: StubResponse | Responder,
|
||||
): FetchStub;
|
||||
/**
|
||||
* Answer `method path` only when `release` is called, for asserting the
|
||||
* pending state in between.
|
||||
*/
|
||||
deferred(
|
||||
method: string,
|
||||
path: string | RegExp,
|
||||
): { release: (response?: StubResponse) => void };
|
||||
/** Every request so far, in order. */
|
||||
requests: RecordedRequest[];
|
||||
/** The requests that hit `method path`. */
|
||||
calls(method: string, path: string | RegExp): RecordedRequest[];
|
||||
}
|
||||
|
||||
let realFetch: typeof fetch | null = null;
|
||||
|
||||
function matches(route: Route, method: string, path: string): boolean {
|
||||
if (route.method !== method) return false;
|
||||
const bare = path.split("?")[0];
|
||||
return typeof route.path === "string"
|
||||
? route.path === bare
|
||||
: route.path.test(path);
|
||||
}
|
||||
|
||||
function envelope({ status = 200, data = null, error }: StubResponse) {
|
||||
const body = error ? { data: null, error } : { data, error: null };
|
||||
return new Response(JSON.stringify(body), {
|
||||
status: error && status === 200 ? 400 : status,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
async function record(
|
||||
input: RequestInfo | URL,
|
||||
init?: RequestInit,
|
||||
): Promise<RecordedRequest> {
|
||||
const request = new Request(input, init);
|
||||
const url = new URL(request.url, window.location.href);
|
||||
const text = request.method === "GET" ? "" : await request.text();
|
||||
let body: unknown = text === "" ? undefined : text;
|
||||
try {
|
||||
if (text !== "") body = JSON.parse(text);
|
||||
} catch {
|
||||
// Keep the raw text.
|
||||
}
|
||||
return {
|
||||
method: request.method,
|
||||
path: `${url.pathname}${url.search}`,
|
||||
headers: request.headers,
|
||||
body,
|
||||
};
|
||||
}
|
||||
|
||||
/** Replace `fetch` for the rest of the test. */
|
||||
export function stubFetch(): FetchStub {
|
||||
realFetch ??= window.fetch;
|
||||
const routes: Route[] = [];
|
||||
const requests: RecordedRequest[] = [];
|
||||
|
||||
window.fetch = async (input, init) => {
|
||||
const request = await record(input, init);
|
||||
requests.push(request);
|
||||
// The newest route wins, so a test can override a default it set up.
|
||||
const route = [...routes]
|
||||
.reverse()
|
||||
.find((r) => matches(r, request.method, request.path));
|
||||
if (!route) {
|
||||
return envelope({
|
||||
status: 404,
|
||||
error: `no stubbed route for ${request.method} ${request.path}`,
|
||||
});
|
||||
}
|
||||
return envelope(await route.respond(request));
|
||||
};
|
||||
|
||||
const stub: FetchStub = {
|
||||
requests,
|
||||
on(method, path, response) {
|
||||
routes.push({
|
||||
method,
|
||||
path,
|
||||
respond: typeof response === "function" ? response : () => response,
|
||||
});
|
||||
return stub;
|
||||
},
|
||||
deferred(method, path) {
|
||||
let release: (response?: StubResponse) => void = () => {};
|
||||
const answer = new Promise<StubResponse>((resolve) => {
|
||||
release = (response = {}) => resolve(response);
|
||||
});
|
||||
routes.push({ method, path, respond: () => answer });
|
||||
return { release: (response) => release(response) };
|
||||
},
|
||||
calls(method, path) {
|
||||
return requests.filter((r) =>
|
||||
matches({ method, path, respond: () => ({}) }, r.method, r.path),
|
||||
);
|
||||
},
|
||||
};
|
||||
return stub;
|
||||
}
|
||||
|
||||
/** Called by `setup.ts` after each test. */
|
||||
export function restoreFetch(): void {
|
||||
if (realFetch) window.fetch = realFetch;
|
||||
realFetch = null;
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* `next/navigation` for the browser project, aliased in `vitest.config.mts`.
|
||||
*
|
||||
* The App Router's hooks throw unless a router is mounted, and mounting one
|
||||
* means booting Next. What a component needs from them is smaller: the
|
||||
* current path and query, and a way to change them. This module answers both
|
||||
* from the page's real `location` and `history`, so `@/lib/url-state` writes
|
||||
* through the same `pushState` / `replaceState` it uses in the app.
|
||||
*
|
||||
* `useSearchParams` follows the address bar the way the router does: it
|
||||
* re-reads on `popstate` and on the URL-state event, one task after the write
|
||||
* rather than synchronously, which is the "adopted a render later" gap the
|
||||
* helper's queue exists for. A test that only asserts what the page shows
|
||||
* never sees the gap; one that writes twice in a row exercises it.
|
||||
*
|
||||
* `redirect` and `notFound` throw like Next's do, so a component that calls
|
||||
* one fails its test loudly instead of rendering past it.
|
||||
*/
|
||||
import { useMemo, useSyncExternalStore } from "react";
|
||||
|
||||
import { URL_STATE_EVENT } from "@/lib/url-state";
|
||||
|
||||
function subscribe(onChange: () => void): () => void {
|
||||
// The router adopts a write after the event loop turns, not inside the
|
||||
// dispatch that announced it.
|
||||
const deferred = () => setTimeout(onChange, 0);
|
||||
window.addEventListener("popstate", deferred);
|
||||
window.addEventListener(URL_STATE_EVENT, deferred);
|
||||
return () => {
|
||||
window.removeEventListener("popstate", deferred);
|
||||
window.removeEventListener(URL_STATE_EVENT, deferred);
|
||||
};
|
||||
}
|
||||
|
||||
const readSearch = () => window.location.search;
|
||||
const readPathname = () => window.location.pathname;
|
||||
|
||||
export function useSearchParams(): URLSearchParams {
|
||||
const search = useSyncExternalStore(subscribe, readSearch, readSearch);
|
||||
return useMemo(() => new URLSearchParams(search), [search]);
|
||||
}
|
||||
|
||||
export function usePathname(): string {
|
||||
return useSyncExternalStore(subscribe, readPathname, readPathname);
|
||||
}
|
||||
|
||||
function navigate(mode: "push" | "replace", href: string): void {
|
||||
const url = new URL(href, window.location.href);
|
||||
if (mode === "push") window.history.pushState(null, "", url);
|
||||
else window.history.replaceState(null, "", url);
|
||||
window.dispatchEvent(new PopStateEvent("popstate"));
|
||||
}
|
||||
|
||||
const router = {
|
||||
push: (href: string) => navigate("push", href),
|
||||
replace: (href: string) => navigate("replace", href),
|
||||
back: () => window.history.back(),
|
||||
forward: () => window.history.forward(),
|
||||
refresh: () => {},
|
||||
prefetch: () => {},
|
||||
};
|
||||
|
||||
export function useRouter(): typeof router {
|
||||
return router;
|
||||
}
|
||||
|
||||
export function useParams(): Record<string, string> {
|
||||
return {};
|
||||
}
|
||||
|
||||
export function useSelectedLayoutSegment(): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
export function useSelectedLayoutSegments(): string[] {
|
||||
return [];
|
||||
}
|
||||
|
||||
export function redirect(href: string): never {
|
||||
throw new Error(`redirect(${href}) called in a browser test`);
|
||||
}
|
||||
|
||||
export function permanentRedirect(href: string): never {
|
||||
throw new Error(`permanentRedirect(${href}) called in a browser test`);
|
||||
}
|
||||
|
||||
export function notFound(): never {
|
||||
throw new Error("notFound() called in a browser test");
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* Render a component the way the app mounts it, in a real browser.
|
||||
*
|
||||
* The providers are the app's own: `I18nProvider` with a real catalog and a
|
||||
* real TanStack `QueryClient`. The signed-in account is seeded into that
|
||||
* client under `queryKeys.authMe()`, exactly where `useAuth` reads it once
|
||||
* `/api/auth/me` has answered, so a component that asks for the account gets
|
||||
* it without a request. Everything else a component fetches goes through the
|
||||
* network and is answered by `stubFetch()` from `./fetch-stub`.
|
||||
*
|
||||
* The app stylesheet is loaded by `setup.ts` for every browser test, so
|
||||
* `hidden`, `pointer-events-none`, popper placement and the breakpoints lay
|
||||
* out as they do in the app.
|
||||
*
|
||||
* const { screen, queryClient } = await renderWithApp(<MeasurementForm />, {
|
||||
* user: { unitPreference: "imperial" },
|
||||
* });
|
||||
* await screen.getByLabelText("Value (lb)").fill("210");
|
||||
*/
|
||||
import type { ReactNode } from "react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { render, type RenderResult } from "vitest-browser-react";
|
||||
|
||||
import type { AuthUser } from "@/hooks/use-auth";
|
||||
import type { Locale } from "@/lib/i18n/config";
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
import { loadMessages } from "@/lib/i18n/load-locale";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
/** A signed-in account with every preference at its default. */
|
||||
export function authUser(overrides: Partial<AuthUser> = {}): AuthUser {
|
||||
return {
|
||||
id: "user-1",
|
||||
username: "user",
|
||||
email: null,
|
||||
role: "USER",
|
||||
heightCm: null,
|
||||
dateOfBirth: null,
|
||||
gender: null,
|
||||
timezone: "UTC",
|
||||
onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
|
||||
onboardingTourCompleted: true,
|
||||
onboardingTourProgress: null,
|
||||
avatarUrl: null,
|
||||
glucoseUnit: null,
|
||||
unitPreference: "metric",
|
||||
timeFormat: "AUTO",
|
||||
dateFormat: "AUTO",
|
||||
disableCoach: false,
|
||||
fullName: null,
|
||||
insurerName: null,
|
||||
insurerIkNumber: null,
|
||||
insuranceNumber: null,
|
||||
lastReportPracticeName: null,
|
||||
reportSelection: null,
|
||||
cycleTrackingEnabled: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
export interface RenderWithAppOptions {
|
||||
/** The reader's language. Its catalog is loaded before the first render. */
|
||||
locale?: Locale;
|
||||
/**
|
||||
* The signed-in account, merged over `authUser()`. `null` leaves the
|
||||
* account unanswered, as before `/api/auth/me` returns.
|
||||
*/
|
||||
user?: Partial<AuthUser> | null;
|
||||
/** Bring a client to seed more reads before rendering. */
|
||||
queryClient?: QueryClient;
|
||||
}
|
||||
|
||||
export interface AppRender {
|
||||
screen: RenderResult;
|
||||
queryClient: QueryClient;
|
||||
}
|
||||
|
||||
/** A client configured like a test should want it: no retries, no refetch. */
|
||||
export function testQueryClient(): QueryClient {
|
||||
return new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false, refetchOnWindowFocus: false },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function renderWithApp(
|
||||
ui: ReactNode,
|
||||
{ locale = "en", user = {}, queryClient }: RenderWithAppOptions = {},
|
||||
): Promise<AppRender> {
|
||||
const client = queryClient ?? testQueryClient();
|
||||
if (user !== null) client.setQueryData(queryKeys.authMe(), authUser(user));
|
||||
if (locale !== "en") await loadMessages(locale);
|
||||
const screen = await render(
|
||||
<QueryClientProvider client={client}>
|
||||
<I18nProvider initialLocale={locale}>{ui}</I18nProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
return { screen, queryClient: client };
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* Setup for the `browser` project (`*.browser.test.tsx`, headless Chromium).
|
||||
*
|
||||
* - The app stylesheet, compiled by Vite through the project's PostCSS
|
||||
* config, so components lay out and hide as they do in the app.
|
||||
* - The EN catalog, the fallback floor of every `t()` chain, loaded through
|
||||
* the production loader. `renderWithApp` loads any other locale it is
|
||||
* asked for.
|
||||
* - After every test: the real `fetch` and the page's starting address come
|
||||
* back, so a stub or a URL write never reaches the next test. Rendered
|
||||
* trees are unmounted by `vitest-browser-react` itself.
|
||||
*/
|
||||
import "@/app/globals.css";
|
||||
|
||||
import { afterEach, beforeAll, beforeEach } from "vitest";
|
||||
|
||||
import { loadMessages } from "@/lib/i18n/load-locale";
|
||||
|
||||
import { restoreFetch } from "./fetch-stub";
|
||||
import { rememberAddress, restoreAddress } from "./url";
|
||||
|
||||
beforeAll(async () => {
|
||||
await loadMessages("en");
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
rememberAddress();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
restoreFetch();
|
||||
restoreAddress();
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* The page's address, for URL-state tests in the browser project.
|
||||
*
|
||||
* Each test file runs in its own page, and `setup.ts` puts the address the
|
||||
* page started on back after every test, so a test may write the URL freely.
|
||||
* Only the query and hash are ever changed: the path is the test runner's
|
||||
* own, and a component that writes state keeps the path it found.
|
||||
*/
|
||||
import { resetUrlStateForTests } from "@/lib/url-state";
|
||||
|
||||
export interface HistoryRecord {
|
||||
/** Every `pushState` and `replaceState` since `recordHistory()`, in order. */
|
||||
writes: Array<{ mode: "push" | "replace"; search: string }>;
|
||||
pushes: () => string[];
|
||||
replaces: () => string[];
|
||||
}
|
||||
|
||||
let restoreHistory: (() => void) | null = null;
|
||||
|
||||
/**
|
||||
* Record history writes without changing them: the real methods still run,
|
||||
* so the page's location moves exactly as it would in the app.
|
||||
*/
|
||||
export function recordHistory(): HistoryRecord {
|
||||
restoreHistory?.();
|
||||
const { history } = window;
|
||||
const push = history.pushState.bind(history);
|
||||
const replace = history.replaceState.bind(history);
|
||||
const writes: HistoryRecord["writes"] = [];
|
||||
const searchOf = (url: string | URL | null | undefined) =>
|
||||
url == null
|
||||
? window.location.search
|
||||
: new URL(url, window.location.href).search;
|
||||
history.pushState = (data, unused, url) => {
|
||||
push(data, unused, url);
|
||||
writes.push({ mode: "push", search: searchOf(url) });
|
||||
};
|
||||
history.replaceState = (data, unused, url) => {
|
||||
replace(data, unused, url);
|
||||
writes.push({ mode: "replace", search: searchOf(url) });
|
||||
};
|
||||
restoreHistory = () => {
|
||||
history.pushState = push;
|
||||
history.replaceState = replace;
|
||||
restoreHistory = null;
|
||||
};
|
||||
return {
|
||||
writes,
|
||||
pushes: () => writes.filter((w) => w.mode === "push").map((w) => w.search),
|
||||
replaces: () =>
|
||||
writes.filter((w) => w.mode === "replace").map((w) => w.search),
|
||||
};
|
||||
}
|
||||
|
||||
/** Start the test on `search` (`""` for a bare path). */
|
||||
export function setSearch(search: string): void {
|
||||
const query = search === "" || search.startsWith("?") ? search : `?${search}`;
|
||||
window.history.replaceState(null, "", `${window.location.pathname}${query}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the query the way the person would from outside the component:
|
||||
* Back, Forward or an edited address. The router hears `popstate`.
|
||||
*/
|
||||
export function navigateExternally(search: string): void {
|
||||
setSearch(search);
|
||||
window.dispatchEvent(new PopStateEvent("popstate"));
|
||||
}
|
||||
|
||||
/** The current query string, `?`-prefixed or empty. */
|
||||
export function currentSearch(): string {
|
||||
return window.location.search;
|
||||
}
|
||||
|
||||
let initialHref: string | null = null;
|
||||
|
||||
/** Called by `setup.ts` before each test. */
|
||||
export function rememberAddress(): void {
|
||||
initialHref = window.location.href;
|
||||
}
|
||||
|
||||
/** Called by `setup.ts` after each test. */
|
||||
export function restoreAddress(): void {
|
||||
restoreHistory?.();
|
||||
resetUrlStateForTests();
|
||||
if (initialHref !== null && window.location.href !== initialHref) {
|
||||
window.history.replaceState(null, "", initialHref);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user