Files
clean-architecture-frontend…/tests/component/chunk-recovery-boundary.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

178 lines
5.7 KiB
TypeScript

// @vitest-environment jsdom
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { lazy, Suspense } from "react";
import { describe, expect, it, vi } from "vitest";
import {
ChunkRecoveryBoundary,
isChunkLoadFailure,
} from "../../src/presentation/boundaries/chunk-recovery-boundary.tsx";
import { FeatureBoundary } from "../../src/presentation/boundaries/render-error-boundary.tsx";
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";
// The states page stands in for a route chunk the network could not deliver:
// a rejected lazy module throws its rejection on every render, as this does.
vi.mock("../../src/presentation/examples/state-gallery-page.tsx", () => ({
default: function UnreachableChunk(): never {
throw new TypeError(
"Failed to fetch dynamically imported module: /assets/states.js",
);
},
}));
function ChunkDefect(): never {
throw new TypeError("Failed to fetch dynamically imported module");
}
function RenderDefect(): never {
throw new Error("ordinary render defect");
}
describe("chunk recovery boundary classification", () => {
it("recognizes lazy module failures without classifying ordinary render errors", () => {
expect(
isChunkLoadFailure(
new TypeError("Failed to fetch dynamically imported module"),
),
).toBe(true);
expect(isChunkLoadFailure(new Error("ordinary render defect"))).toBe(false);
});
it("recognizes the WebKit module failure and the Vite CSS preload failure", () => {
expect(
isChunkLoadFailure(new TypeError("Importing a module script failed.")),
).toBe(true);
expect(
isChunkLoadFailure(
new Error("Unable to preload CSS for /assets/states-3f2a.css"),
),
).toBe(true);
});
it("recovers when Vite rethrows a vite:preloadError into the lazy import", async () => {
// Vite dispatches `vite:preloadError` and, unless a listener prevents it,
// rejects the dynamic import with the same error. That rejection is what
// reaches this boundary.
const Page = lazy(() =>
Promise.reject(new Error("Unable to preload CSS for /assets/states.css")),
);
const recover = vi.fn(async () => ({
action: "support" as const,
reason: "reload-already-attempted",
}));
render(
<Suspense fallback={null}>
<ChunkRecoveryBoundary chunkId="route-states" recover={recover}>
<Page />
</ChunkRecoveryBoundary>
</Suspense>,
);
expect(
await screen.findByRole("heading", {
name: "화면 자산을 복구하지 못했습니다.",
}),
).toBeVisible();
expect(recover).toHaveBeenCalledWith({
chunkId: "route-states",
failureKind: "CHUNK_LOAD_FAILURE",
});
});
it("runs the recovery input only for a lazy chunk rejection", async () => {
const recover = vi.fn(async () => ({
action: "support" as const,
reason: "reload-already-attempted",
}));
render(
<ChunkRecoveryBoundary chunkId="route-home" recover={recover}>
<ChunkDefect />
</ChunkRecoveryBoundary>,
);
expect(
await screen.findByRole("heading", {
name: "화면 자산을 복구하지 못했습니다.",
}),
).toBeVisible();
expect(recover).toHaveBeenCalledOnce();
expect(recover).toHaveBeenCalledWith({
chunkId: "route-home",
failureKind: "CHUNK_LOAD_FAILURE",
});
});
it("rethrows an ordinary component defect to the local render boundary", () => {
const recover = vi.fn();
render(
<FeatureBoundary routeId="APP_HOME" buildId="build-a">
<ChunkRecoveryBoundary chunkId="route-home" recover={recover}>
<RenderDefect />
</ChunkRecoveryBoundary>
</FeatureBoundary>,
);
expect(screen.getByRole("alert")).toHaveTextContent(
"화면을 표시하지 못했습니다.",
);
expect(recover).not.toHaveBeenCalled();
});
it("offers a user-started reload on the failure surface", async () => {
render(
<ChunkRecoveryBoundary
chunkId="route-home"
recover={async () => ({
action: "support" as const,
reason: "reload-already-attempted",
})}
>
<ChunkDefect />
</ChunkRecoveryBoundary>,
);
expect(
await screen.findByRole("button", { name: "한 번 새로고침" }),
).toBeVisible();
});
it("clears a failed route chunk when the user moves to a sibling route", async () => {
// React Router reuses the rendered-route instance between sibling routes,
// so a failure latched in one route's boundary would otherwise follow the
// user to every other page until a full reload.
const user = userEvent.setup();
window.history.pushState({}, "", "/examples/states");
render(
<ApplicationProvider application={createTestApplication()}>
<PreferenceProviders>
<AppRouter />
</PreferenceProviders>
</ApplicationProvider>,
);
expect(
await screen.findByRole("heading", {
name: "화면 자산을 복구하지 못했습니다.",
}),
).toBeVisible();
await user.click(screen.getAllByRole("link", { name: "UI 구성요소" })[0]!);
expect(
await screen.findByRole(
"heading",
{ name: "UI 구성요소", level: 1 },
{ timeout: 5000 },
),
).toBeVisible();
expect(
screen.queryByRole("heading", { name: "화면 자산을 복구하지 못했습니다." }),
).toBeNull();
});
});