Files
clean-architecture-frontend…/tests/component/router.test.tsx
T
DongHyeonkaandClaude Opus 5.5 ddf74ed6e9 fix(presentation): keep preferences above the scope fence, dispose routers (R-8.3)
LocaleProvider and ThemeProvider lived inside AppRouter, below the
server-state scope fence (and below QueryClientProvider keyed by
generation). A session change (FENCED -> READY) unmounted and remounted
them, so their live state was thrown away and re-read from storage. The
browser router was created in useMemo and never disposed, so every
remount (and StrictMode's double useMemo) left a popstate listener behind.

- New presentation/providers/preference-providers.tsx: persisted
  LocaleProvider + ThemeProvider (the wiring T45 added to AppRouter).
- bootstrap/runtime-application.tsx: ApplicationProvider >
  PreferenceProviders > ServerStateGenerationProvider > AppRouter, so the
  fence only remounts session-scoped UI.
- AppRouter no longer mounts Locale/Theme. It creates the router in the
  effect that disposes it: a disposed router never listens to history
  again, so useMemo + cleanup would break back/forward under StrictMode's
  replayed mount.
- Tests that mount AppRouter directly now wrap it in PreferenceProviders
  (router, chunk-recovery-boundary, app-shell, product-feature-switch,
  locale-platform, reference-feature reference-page).

Verified: RED "keeps locale state across a session scope fence and
disposes routers" (RuntimeApplication, demo sign-in, storage cleared after
choosing en-US) came back in Korean before and passes after; with the
providers hoisted but no dispose it fails on popstate listeners (4 added,
0 removed). check:architecture, check:types:app, check:types:test, lint,
test:component, test:reference-feature pass; test:unit passes except the
pre-existing removal-fixture test (needs generated artifacts/ files absent
from a fresh worktree).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 12:39:51 +09:00

222 lines
7.3 KiB
TypeScript

// @vitest-environment jsdom
import { act, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { createAnonymousSessionAdapter } from "../../src/adapters/auth/external-session-adapter.ts";
import type { ApplicationOutputPorts } from "../../src/application/create-application.ts";
import { INSTALLED_PRODUCT_FEATURE_IDS } from "../../src/features/installed-product-manifest.ts";
import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx";
import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx";
import { AppRouter } from "../../src/presentation/routes/app-router.tsx";
import { createTestApplication } from "../helpers/create-test-application.ts";
import { createProductFeaturesStub } from "../helpers/runtime-capabilities-stub.ts";
function renderRouter(
diagnostics: ApplicationOutputPorts["diagnostics"] = { record: () => {} },
productFeatures?: ApplicationOutputPorts["productFeatures"],
) {
return render(
<ApplicationProvider
application={createTestApplication({
session: createAnonymousSessionAdapter(),
diagnostics,
...(productFeatures ? { productFeatures } : {}),
})}
>
<PreferenceProviders>
<AppRouter />
</PreferenceProviders>
</ApplicationProvider>,
);
}
/** A back/forward style navigation that leaves focus where the user left it. */
function navigateByHistory(url: string) {
act(() => {
window.history.pushState({}, "", url);
window.dispatchEvent(new PopStateEvent("popstate"));
});
}
function routeChangeReports(record: ReturnType<typeof vi.fn>) {
return record.mock.calls.filter(
([event]) => (event as { eventId: string }).eventId === "route.changed",
).length;
}
describe("generic application router", () => {
it("reaches the platform overview from the home starter actions", async () => {
const user = userEvent.setup();
window.history.pushState({}, "", "/");
renderRouter();
// The starter action lives inside the lazily loaded home chunk, so this is
// the first wait in the file that has to outlast a chunk load rather than
// an already-mounted shell element.
await user.click(
await screen.findByRole(
"link",
{ name: "플랫폼 구성 보기" },
{ timeout: 5000 },
),
);
await waitFor(() =>
expect(
screen.getByRole("heading", { name: "플랫폼 구성", level: 1 }),
).toHaveFocus(),
);
});
it("renders the app shell and not-found route without a feature input", async () => {
window.history.pushState({}, "", "/missing");
renderRouter();
expect(
await screen.findByRole("heading", {
name: "페이지를 찾을 수 없습니다.",
}),
).toBeVisible();
expect(screen.getByRole("navigation", { name: "주요 탐색" })).toBeVisible();
expect(screen.getByRole("main")).toBeVisible();
});
it("navigates between registry-backed platform routes", async () => {
const user = userEvent.setup();
window.history.pushState({}, "", "/");
renderRouter();
await user.click(
await screen.findByRole("link", { name: "UI 구성요소" }),
);
expect(
await screen.findByRole("heading", { name: "UI 구성요소", level: 1 }),
).toBeVisible();
expect(window.location.pathname).toBe("/examples/ui");
await waitFor(() =>
expect(document.title).toBe("UI 구성요소 · Frontend Skeleton"),
);
await waitFor(() =>
expect(
screen.getByRole("heading", { name: "UI 구성요소", level: 1 }),
).toHaveFocus(),
);
});
it("changes only the title and copy when the locale changes", async () => {
// docs/architecture/routing-pages-and-patterns.md §9: a locale change
// re-renders the document title and copy; it is not a route change.
const user = userEvent.setup();
const record = vi.fn();
window.history.pushState({}, "", "/missing");
renderRouter({ record });
await waitFor(() =>
expect(
screen.getByRole("heading", {
name: "페이지를 찾을 수 없습니다.",
level: 1,
}),
).toHaveFocus(),
);
const reportsBefore = routeChangeReports(record);
expect(reportsBefore).toBeGreaterThan(0);
const localeSelect = screen.getByLabelText("언어");
await user.selectOptions(localeSelect, "en-US");
await waitFor(() =>
expect(document.title).toBe("Page not found · Frontend Skeleton"),
);
expect(
screen.getByRole("heading", { name: "Page not found.", level: 1 }),
).toBeVisible();
expect(localeSelect).toHaveFocus();
expect(routeChangeReports(record)).toBe(reportsBefore);
});
it.each([
{
surface: "authentication-required",
url: "/examples/reference-resources",
routeId: "REFERENCE_RESOURCE_LIST",
title: "Reference resources · Frontend Skeleton",
disableFeature: false,
},
{
surface: "invalid-route",
url: "/examples/ui?unexpected=1",
routeId: "EXAMPLES_UI",
title: "UI 구성요소 · Frontend Skeleton",
disableFeature: false,
},
{
surface: "disabled-feature",
url: "/examples/reference-resources",
routeId: "REFERENCE_RESOURCE_LIST",
title: "Reference resources · Frontend Skeleton",
disableFeature: true,
},
])(
"runs the route lifecycle on the $surface surface",
async ({ surface, url, routeId, title, disableFeature }) => {
const record = vi.fn();
window.history.pushState({}, "", "/");
const { container } = renderRouter(
{ record },
disableFeature
? createProductFeaturesStub({
[INSTALLED_PRODUCT_FEATURE_IDS[0]!]: "DISABLED_BY_CONFIG",
})
: undefined,
);
const link = (
await screen.findAllByRole("link", { name: "UI 구성요소" })
)[0]!;
link.focus();
navigateByHistory(url);
await waitFor(
() =>
expect(
container.querySelector(`[data-surface="${surface}"]`),
).not.toBeNull(),
{ timeout: 5000 },
);
await waitFor(() => expect(document.title).toBe(title));
expect(
screen.getByRole("main").contains(document.activeElement),
).toBe(true);
expect(record).toHaveBeenCalledWith(
expect.objectContaining({
eventId: "route.changed",
context: expect.objectContaining({ route_id: routeId }),
}),
);
},
);
it("focuses the route heading again when the lazy chunk is already cached", async () => {
// §9.7. The first visit resolves the route module asynchronously, so the
// router lifecycle and the page header commit separately. A later visit
// renders the cached module in the same commit, which is the ordering that
// must still hand focus to the heading rather than leaving it on main.
const user = userEvent.setup();
window.history.pushState({}, "", "/");
renderRouter();
for (const label of ["UI 구성요소", "화면 상태", "UI 구성요소"]) {
await user.click(await screen.findByRole("link", { name: label }));
await waitFor(() =>
expect(
screen.getByRole("heading", { name: label, level: 1 }),
).toHaveFocus(),
);
}
});
});