Files
gerbeur/src/test/render.tsx
khannurien d392be7cb8
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 50s
v3: api/ gets one layout rule and keeps to it, and whatever crosses the wire is defined once, in shared/ — api/model/interfaces.ts and src/model.ts declared the same 40 types by hand and had drifted: the error envelope, email required on one side and optional on the other, Invitee/InviteTreeEntry and LinkPreview/UrlPreviewResponse for one shape each. The validation limits, the role permissions, the chat length cap, the @mention pattern and the Bandcamp and YouTube player responses were copied too, behind "keep in sync" comments. shared/ now holds them once, one file per domain (api, category, chat, comment, dump, follow, mention, notification, permissions, player, playlist, search, user, validation, ws), and imports nothing from either half. The server sends Dates; the client reads Wire<T>, the same type with every Date an ISO string, and turns it back with src/utils/shared/deserialize.ts. APIErrorCode becomes a const object, since the frontend's erasableSyntaxOnly rejects an enum. The shared types showed two real gaps: the avatar upload and GET /api/users/me return the full self user and the frontend read them as public users, and a stored session may predate media tokens, so the client keeps it as its own Session type. The backend rule: each folder holds one kind of module, each file is named after its domain. routes/ parse and answer; services/ hold the logic and every SQL query (lib/auth.ts's token check moves to user-service); remote/ is the only place that fetches from other sites — the guarded fetch and the HTML scraping out of rich-content-service, public-address, the Bandcamp and YouTube resolvers, the link providers, the image proxy (fetch, checks and cache, out of routes/preview.ts) and the Twemoji glyphs (out of lib/site-icons.ts). model/ holds per table a row type, its guard and its mappers; validators/ the request guards; db/connection.ts the handle and transaction(), db/startup.ts the purges and default admin that db.ts ran on import, called at the same moment. Tests mirror the source one file per module, test/<layer>/<module>.test.ts, with shared/'s under shared/test/ (deno task test runs both); the test that covered the bandcamp and soundcloud providers together is two now, and the backend can() has its own, so 202 tests. deno lint src/ is clean too: window.* becomes globalThis.*, and test bodies and act() callbacks that never awaited lose their async. The README states the rule. No behaviour changes; the catalogues only move their source references.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 20:19:48 +00:00

266 lines
9.0 KiB
TypeScript

import { type ReactElement, type ReactNode, useState } from "react";
import { render, type RenderOptions } from "@testing-library/react";
import { I18nProvider } from "@lingui/react";
import { i18n } from "@lingui/core";
import { MemoryRouter, Route, Routes, useLocation } from "react-router";
import type { Session } from "../utils/auth/storage.ts";
import type { Category } from "../../shared/category.ts";
import { AuthContext } from "../contexts/auth/AuthContext.ts";
import { AuthProvider } from "../contexts/auth/AuthProvider.tsx";
import {
defaultWSChatValue,
defaultWSPresenceValue,
defaultWSValue,
WSChatContext,
type WSChatContextValue,
WSContext,
type WSContextValue,
WSPresenceContext,
type WSPresenceContextValue,
} from "../contexts/ws/WSContext.ts";
import { WSProvider } from "../contexts/ws/WSProvider.tsx";
import {
defaultFollowValue,
FollowContext,
type FollowContextValue,
} from "../contexts/social/FollowContext.ts";
import { FollowProvider } from "../contexts/social/FollowProvider.tsx";
import {
CategoriesContext,
type CategoriesContextValue,
} from "../contexts/category/CategoriesContext.ts";
import { CategoriesProvider } from "../contexts/category/CategoriesProvider.tsx";
import {
defaultPlayerTimeValue,
defaultPlayerValue,
PlayerContext,
type PlayerContextValue,
PlayerTimeContext,
type PlayerTimeValue,
} from "../contexts/player/PlayerContext.ts";
import { PlayerProvider } from "../contexts/player/PlayerProvider.tsx";
import { ThemeProvider } from "../contexts/theme/ThemeProvider.tsx";
import { ChatProvider } from "../contexts/chat/ChatProvider.tsx";
import { route } from "./fetch.ts";
import { storeSession } from "./fixtures.ts";
/** Renders the current location into the DOM, for asserting navigation. */
export function LocationProbe() {
const loc = useLocation();
return (
<div
hidden
data-testid="location"
data-state={JSON.stringify(loc.state ?? null)}
>
{loc.pathname + loc.search}
</div>
);
}
/** The path the probe last saw. */
export function currentPath(): string {
return document.querySelector('[data-testid="location"]')?.textContent ?? "";
}
interface RouterOptions {
/** Initial URL, or several for a history stack (the last is current). */
route?: string | string[];
/** Route pattern the element is mounted on, for useParams. */
path?: string;
/** Extra routes to mount next to it, e.g. a redirect target. */
extraRoutes?: ReactNode;
}
function Router(
{ children, route = "/", path = "*", extraRoutes }: RouterOptions & {
children: ReactNode;
},
) {
const entries = Array.isArray(route) ? route : [route];
return (
<MemoryRouter initialEntries={entries} initialIndex={entries.length - 1}>
<Routes>
<Route path={path} element={children} />
{extraRoutes}
</Routes>
<LocationProbe />
</MemoryRouter>
);
}
// ── Stubbed contexts ─────────────────────────────────────────────────────────
export interface StubOptions extends RouterOptions {
session?: Session | null;
/** Any of the socket's three contexts' fields; each goes to its own. */
ws?: Partial<WSContextValue & WSChatContextValue & WSPresenceContextValue>;
follows?: Partial<FollowContextValue>;
categories?: Category[] | Partial<CategoriesContextValue>;
player?: Partial<PlayerContextValue & PlayerTimeValue>;
}
function StubAuth(
{ session, children }: { session: Session | null; children: ReactNode },
) {
const [authResponse, setAuthResponse] = useState(session);
return (
<AuthContext.Provider value={{ authResponse, setAuthResponse }}>
{children}
</AuthContext.Provider>
);
}
/** `defaults`, with whichever of its keys `overrides` sets. */
function pick<T extends object>(defaults: T, overrides: object = {}): T {
const out = { ...defaults };
for (const key of Object.keys(defaults) as (keyof T)[]) {
if (key in overrides) {
out[key] = (overrides as T)[key];
}
}
return out;
}
function categoriesValue(
c: StubOptions["categories"],
): CategoriesContextValue {
const list = Array.isArray(c) ? c : c?.categories ?? [];
return {
categories: list,
byId: new Map(list.map((x) => [x.id, x])),
isLoaded: true,
refresh: async () => {},
...(Array.isArray(c) ? {} : c),
};
}
/**
* Renders `ui` with context values supplied directly — no network, no socket.
* For components whose inputs are the contexts they read.
*/
export function renderWithContexts(
ui: ReactElement,
opts: StubOptions = {},
renderOptions?: RenderOptions,
) {
// A wrapper rather than one tree, so `rerender(ui)` keeps the contexts.
const Wrapper = ({ children }: { children: ReactNode }) => (
<I18nProvider i18n={i18n}>
<StubAuth session={opts.session ?? null}>
<PlayerContext.Provider
value={{ ...defaultPlayerValue, ...opts.player }}
>
<PlayerTimeContext.Provider
value={{
currentTime: opts.player?.currentTime ??
defaultPlayerTimeValue.currentTime,
duration: opts.player?.duration ??
defaultPlayerTimeValue.duration,
}}
>
<WSContext.Provider value={pick(defaultWSValue, opts.ws)}>
<WSChatContext.Provider value={pick(defaultWSChatValue, opts.ws)}>
<WSPresenceContext.Provider
value={pick(defaultWSPresenceValue, opts.ws)}
>
<FollowContext.Provider
value={{
...defaultFollowValue,
isLoaded: true,
...opts.follows,
}}
>
<CategoriesContext.Provider
value={categoriesValue(opts.categories)}
>
<Router {...opts}>{children}</Router>
</CategoriesContext.Provider>
</FollowContext.Provider>
</WSPresenceContext.Provider>
</WSChatContext.Provider>
</WSContext.Provider>
</PlayerTimeContext.Provider>
</PlayerContext.Provider>
</StubAuth>
</I18nProvider>
);
return render(ui, { ...renderOptions, wrapper: Wrapper });
}
// ── The real providers ───────────────────────────────────────────────────────
export interface AppOptions extends RouterOptions {
/** Signed in as this session (stored before mount, as after a login). */
session?: Session | null;
categories?: Category[];
}
/** The routes every provider tree calls on mount, as fallbacks: a test's
* own routes for the same paths win, whenever they were added. */
export function defaultRoutes(
{ session, categories = [] }: Pick<AppOptions, "session" | "categories"> = {},
) {
const fallback = { fallback: true };
route(
"GET /api/categories",
() => categories.map((c) => JSON.parse(JSON.stringify(c))),
fallback,
);
route("GET /api/follows/status", () => ({
followedUserIds: [],
followedPlaylistIds: [],
}), fallback);
// Standing, not fallbacks: a page test's own `GET /api/users/:u` would
// otherwise answer for "me" and hand the session someone else's role.
route(
"GET /api/users/me",
() => JSON.parse(JSON.stringify(session?.user ?? null)),
);
route("GET /api/users/me/media-token", () => ({ mediaToken: "media-token" }));
}
/**
* Renders `ui` inside the same provider tree as App — real auth, socket (a
* FakeWebSocket), follows, categories, player and chat — over a memory router.
* Register routes the page needs with `route()` before or after calling this;
* the defaults for the providers' own requests are installed first so a test
* can override them.
*/
export function renderApp(ui: ReactElement, opts: AppOptions = {}) {
if (opts.session) storeSession(opts.session);
defaultRoutes(opts);
const { route: initial = "/", path = "*", extraRoutes } = opts;
const entries = Array.isArray(initial) ? initial : [initial];
const Wrapper = ({ children }: { children: ReactNode }) => (
<I18nProvider i18n={i18n}>
<ThemeProvider>
<AuthProvider>
<PlayerProvider>
<WSProvider>
<FollowProvider>
<CategoriesProvider>
<MemoryRouter
initialEntries={entries}
initialIndex={entries.length - 1}
>
<ChatProvider>
<Routes>
<Route path={path} element={children} />
{extraRoutes}
</Routes>
<LocationProbe />
</ChatProvider>
</MemoryRouter>
</CategoriesProvider>
</FollowProvider>
</WSProvider>
</PlayerProvider>
</AuthProvider>
</ThemeProvider>
</I18nProvider>
);
return render(ui, { wrapper: Wrapper });
}