문제: RouteLifecycle이 pathname·search·navigationType을 effect 의존값으로 썼다. 그래서 URL에 묶은 필터를 바꾸면 포커스가 컨트롤에서 <main>으로 튀고, POP이 아니면 맨 위로 스크롤하고, route.changed를 한 번 더 남겼다. 이미 보고 있는 화면의 링크를 눌러도(React Router가 REPLACE로 바꿈) navigationType만 바뀌어 같은 일이 났다. 템플릿은 필터를 URL에 두라고 권하므로 첫 목록 화면에서 바로 드러난다(WCAG 3.2.2). 고른 방법: 이동 판단을 route ID 또는 pathname 변경으로 좁혔다(리뷰 5.1 (B)). 포커스·스크롤·진단은 useEffectEvent로 옮겨 navigationType을 읽기만 하고 트리거로 쓰지 않는다. 검색값 변경에 맨 위가 필요한 화면(페이지 번호)은 그 화면이 직접 스크롤한다. routing 문서 6.3절에 규칙을 적었다. 버린 대안: (C) 라우트 계약에 searchChangeIsNavigation 선언 — 그런 라우트가 템플릿에 없고 생성기·문서까지 바뀐다. 필요해지면 (B) 위에 더할 수 있다. navigationType을 ref로 들고 있기 — 렌더 중 ref 쓰기라 React 19의 useEffectEvent보다 의도가 덜 드러난다. 위험·한계: 지금 검색값 변경을 이동으로 세던 대시보드가 있다면 수치가 준다. 실제 브라우저의 스크롤 유지는 jsdom이 스크롤을 건너뛰어 정적 확인만 했다. 테스트용 fixture 페이지에 URL에 묶은 select를 더했다. 검증: - RED: router.test.tsx 새 테스트 2건이 수정 전 실패. 포커스가 <main id="main-content">에 있었고 route.changed가 필터 테스트 1→3, 링크 테스트 1→2로 늘었다. - GREEN: router.test.tsx 11/11, tests/component 34 files 213 tests 통과. tsc(app, test) 통과, eslint(바꾼 파일) 통과, verify-documentation-readiness PASS_SCOPED. - check:architecture는 pnpm 실행을 요구해 이 worktree에서 미실행. Refs: docs/reviews/2026-11-01-maturity-review/08-presentation.md 08-02
291 lines
10 KiB
TypeScript
291 lines
10 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";
|
|
|
|
// Feature-route surfaces run against a test-only feature, not the removable
|
|
// sample (FE-GATE-020 runs this file after deleting the sample).
|
|
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("reaches the platform overview from the home starter actions", async () => {
|
|
const user = userEvent.setup();
|
|
window.history.pushState({}, "", "/");
|
|
renderRouter();
|
|
|
|
await user.click(
|
|
await screen.findByRole("link", { name: "플랫폼 구성 보기" }),
|
|
);
|
|
|
|
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: "/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 = (
|
|
await screen.findAllByRole("link", { name: "UI 구성요소" })
|
|
)[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({}, "", "/examples/ui");
|
|
renderRouter({ record });
|
|
|
|
await waitFor(() =>
|
|
expect(
|
|
screen.getByRole("heading", { name: "UI 구성요소", level: 1 }),
|
|
).toHaveFocus(),
|
|
);
|
|
const reportsBefore = routeChangeReports(record);
|
|
const link = within(
|
|
screen.getByRole("navigation", { name: "주요 탐색" }),
|
|
).getByRole("link", { name: "UI 구성요소" });
|
|
await user.click(link);
|
|
|
|
expect(link).toHaveFocus();
|
|
expect(routeChangeReports(record)).toBe(reportsBefore);
|
|
});
|
|
|
|
it("ignores unknown query parameters on a platform route 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({}, "", "/examples/ui?utm_source=mail#top");
|
|
const { container } = renderRouter();
|
|
|
|
expect(
|
|
await screen.findByRole(
|
|
"heading",
|
|
{ name: "UI 구성요소", level: 1 },
|
|
),
|
|
).toBeVisible();
|
|
expect(container.querySelector('[data-surface="invalid-route"]')).toBeNull();
|
|
await waitFor(() =>
|
|
expect(document.title).toBe("UI 구성요소 · Frontend Skeleton"),
|
|
);
|
|
expect(`${window.location.pathname}${window.location.search}`).toBe(
|
|
"/examples/ui?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 ["UI 구성요소", "화면 상태", "UI 구성요소"]) {
|
|
await user.click(await screen.findByRole("link", { name: label }));
|
|
await waitFor(() =>
|
|
expect(
|
|
screen.getByRole("heading", { name: label, level: 1 }),
|
|
).toHaveFocus(),
|
|
);
|
|
}
|
|
});
|
|
});
|