Files
clean-architecture-frontend…/tests/component/router.test.tsx
T
DongHyeonka e632b230e3 docs: 옮긴 문서를 가리키는 링크와 경로를 새 위치로 고친다
문제: 앞 커밋이 기록·설계서·결정 기록을 옮겨서, 그 문서를 가리키는
상대 링크 182개와 살아 있는 문서·코드 주석의 경로 23곳이 없는 곳을
가리킨다.

고른 방법: 기계적으로 바꾼다.
- 상대 링크: 모든 .md(기록 포함)에서 옮기기 전 트리로 대상을 풀고,
  대상이나 문서 자신이 옮겨졌으면 새 위치 기준 상대 경로로 다시 쓴다.
  옮기기 전에도 없던 대상은 건드리지 않는다. 기록 본문에서 고친 것은
  링크 대상뿐이다(백엔드 1단계와 같은 예외).
- 경로 글자: 살아 있는 문서와 코드·설정 주석의 `docs/architecture/…`,
  `docs/superpowers/…`, `decisions/VD-…`를 새 경로로 바꾼다. 기록 본문과
  CHANGELOG.md는 쓴 때의 경로를 그대로 둔다. review-evidence.md와
  review-ledger.json의 `docs/superpowers/specs/…`는 이 트리가 아닌 검토
  작업 공간의 출처 표시라 그대로 둔다.

위험: 경로 글자를 바꾼 곳은 주석과 문서뿐이고 실행 코드의 경로 상수는
없다. 문서 지도(docs/README.md)의 옛 폴더 행은 뒤 커밋이 다시 쓴다.

검증: `git grep -n -E "docs/superpowers|architecture/decisions"`가 기록,
CHANGELOG.md, 출처 표시 두 곳, docs/README.md·README.md(뒤에서 다시
쓴다) 밖에서 0건.
2026-11-08 17:25:41 +09:00

280 lines
9.8 KiB
TypeScript

// @vitest-environment jsdom
import { act, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import {
createAnonymousSessionAdapter,
createDemoSessionAdapter,
} 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";
// Routes and pages come from a test-only feature, not the removable sample
// (FE-GATE-020 runs this file after deleting the sample) nor the starter
// screens a product replaces (0929/10-02; starter-*.test.tsx test those).
vi.mock("../../src/.generated/product-feature-index.ts", async () => ({
DECLARED_PRODUCT_FEATURE_IDS: ["fixture-feature"],
PRODUCT_FEATURE_MODULES: [(await import("../helpers/fixture-feature.tsx")).FIXTURE_FEATURE_MODULE],
}));
vi.mock("../../src/.generated/product-context-index.ts", async () => ({
PRODUCT_CONTEXT_MODULES: [(await import("../helpers/fixture-feature.tsx")).FIXTURE_CONTEXT_MODULE],
}));
function renderRouter(
diagnostics: ApplicationOutputPorts["diagnostics"] = { record: () => {} },
productFeatures?: ApplicationOutputPorts["productFeatures"],
session: ApplicationOutputPorts["session"] = createAnonymousSessionAdapter(),
) {
return render(
<ApplicationProvider
application={createTestApplication({
session,
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("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 routes", async () => {
const user = userEvent.setup();
window.history.pushState({}, "", "/");
renderRouter();
await user.click(
await screen.findByRole("link", { name: "Fixture first page" }),
);
expect(
await screen.findByRole("heading", { name: "Fixture first page", level: 1 }),
).toBeVisible();
expect(window.location.pathname).toBe("/fixture/first");
await waitFor(() =>
expect(document.title).toBe("Fixture first page · Frontend Skeleton"),
);
await waitFor(() =>
expect(
screen.getByRole("heading", { name: "Fixture first page", level: 1 }),
).toHaveFocus(),
);
});
it("changes only the title and copy when the locale changes", async () => {
// docs/design/2026-07-26-routing-pages-and-patterns-design.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: "/fixture/items",
routeId: "FIXTURE_ITEMS",
title: "Fixture items · Frontend Skeleton",
disableFeature: false,
},
{
surface: "invalid-route",
url: "/fixture/items?limit=invalid",
routeId: "FIXTURE_ITEMS",
title: "Fixture items · Frontend Skeleton",
disableFeature: false,
},
{
surface: "disabled-feature",
url: "/fixture/items",
routeId: "FIXTURE_ITEMS",
title: "Fixture items · 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 = within(
await screen.findByRole("navigation", { name: "주요 탐색" }),
).getAllByRole("link")[0]!;
link.focus();
navigateByHistory(url);
await waitFor(
() =>
expect(
container.querySelector(`[data-surface="${surface}"]`),
).not.toBeNull(),
);
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("keeps focus and scroll on a control that changes only the URL query", async () => {
// 08-02. A list filter bound to the query is input on the same screen
// (WCAG 3.2.2), not a route change: focus stays on the control and no
// second route.changed is reported.
const user = userEvent.setup();
const record = vi.fn();
window.history.pushState({}, "", "/fixture/items");
renderRouter({ record }, undefined, createDemoSessionAdapter("authenticated"));
const filter = await screen.findByLabelText("Fixture limit");
await waitFor(() => expect(routeChangeReports(record)).toBe(1));
await user.selectOptions(filter, "50");
await waitFor(() => expect(window.location.search).toBe("?limit=50"));
expect(filter).toHaveValue("50");
expect(filter).toHaveFocus();
expect(routeChangeReports(record)).toBe(1);
});
it("leaves focus on a link that names the page already shown", async () => {
// 08-02. React Router turns a link to the current URL into a REPLACE; the
// navigation type changes but the screen does not.
const user = userEvent.setup();
const record = vi.fn();
window.history.pushState({}, "", "/fixture/first");
renderRouter({ record });
await waitFor(() =>
expect(
screen.getByRole("heading", { name: "Fixture first page", level: 1 }),
).toHaveFocus(),
);
const reportsBefore = routeChangeReports(record);
const link = within(
screen.getByRole("navigation", { name: "주요 탐색" }),
).getByRole("link", { name: "Fixture first page" });
await user.click(link);
expect(link).toHaveFocus();
expect(routeChangeReports(record)).toBe(reportsBefore);
});
it("ignores unknown query parameters on a route without a search codec and keeps the URL", async () => {
// D-16: `/?utm_source=x` or an OAuth callback parameter is not an invalid
// address. The `none` codec drops it from the parsed input only.
window.history.pushState({}, "", "/fixture/first?utm_source=mail#top");
const { container } = renderRouter();
expect(
await screen.findByRole(
"heading",
{ name: "Fixture first page", level: 1 },
),
).toBeVisible();
expect(container.querySelector('[data-surface="invalid-route"]')).toBeNull();
await waitFor(() =>
expect(document.title).toBe("Fixture first page · Frontend Skeleton"),
);
expect(`${window.location.pathname}${window.location.search}`).toBe(
"/fixture/first?utm_source=mail",
);
});
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 [
"Fixture first page",
"Fixture second page",
"Fixture first page",
]) {
await user.click(await screen.findByRole("link", { name: label }));
await waitFor(() =>
expect(
screen.getByRole("heading", { name: label, level: 1 }),
).toHaveFocus(),
);
}
});
});