Files
clean-architecture-frontend…/tests/component/router.test.tsx
T
DongHyeonka c03bf020c9 test(setup): Testing Library 대기 기한을 전역 한 곳에서 정한다 (0929/10-01)
문제
lazy route 화면을 findBy*·waitFor 기본값(1초)으로 기다리는 테스트가 1코어
부하에서 코드와 무관하게 떨어진다. 수정 전 재현에서
runtime-application.test.tsx:65 "Unable to find role=heading name=Clean
Architecture Frontend"와 reference-production-vertical.test.tsx:103
"Unable to find role=button name=로그인 시작"이 났다. 두 DOM 모두
route-loading(aria-busy) 상태였다. 지난 리뷰는 router.test.tsx:244-250도
같은 이유로 실패했다고 적었다. React 19는 Suspense를 풀 때마다 실제 300ms
타이머(FALLBACK_THROTTLE_MS)를 기다린다. context route 표와 lazy 페이지를
거치는 화면은 렌더링 전에 1초 중 600ms를 쓴다. 이 사정을 아는 파일만
호출마다 { timeout: 5000 }을 붙이거나(7개 파일 13곳) 파일 단위로
configure를 바꿨다(reference-page). 새 테스트 작성자는 이 규칙을 알 방법이
없다.

고른 방법
tests/setup.ts에서 configure({ asyncUtilTimeout: 5_000 })를 한 번 정하고,
같은 값을 반복하던 호출·파일 단위 override를 지웠다. findBy*·waitFor는
DOM 변화가 오면 바로 끝나므로 기한은 멈춤을 알리는 용도뿐이다. 10초 테스트
제한의 절반이라 진짜 멈춤은 여전히 Testing Library의 DOM 덤프와 함께
실패한다. 기한을 늘리는 방식이라 고른 이유를 setup에 주석으로 남겼다.

버린 대안
- 가짜 시계: Testing Library는 Jest의 가짜 타이머만 알아본다
  (jestFakeTimersAreEnabled가 jest 전역을 본다). Vitest 가짜 타이머에서
  waitFor는 자기 타이머가 멈춰 끝나지 않는다. MSW와 user-event도 실제
  시계로 돈다.
- route chunk를 테스트에서 미리 import하기: chunk를 받아도 React의 300ms
  reveal 타이머와 렌더링 비용은 그대로 기한 안에 남는다. 테스트가 route
  모듈 목록을 따로 알아야 한다.
- 실패한 파일에만 timeout 붙이기: 지금 상태와 같다. 다음 lazy 화면
  테스트에서 같은 실패가 반복된다.

위험·한계
- 기다리다 실패하는 테스트는 실패까지 1초가 아니라 5초 걸린다. 부재를
  findBy·waitFor의 실패로 확인하는 테스트는 없다(grep으로 확인).
- 가짜 타이머를 쓰는 테스트의 waitFor는 이 값과 무관하다(가짜 시간).

검증
- RED(수정 전, taskset -c 0 + 같은 코어의 바쁜 이웃 1개, --maxWorkers=4,
  component·features·integration·platform/cardinality): 3회 중 1회 위 두
  테스트 실패.
- GREEN(같은 조건): 대상 6개 파일 6회, 넓은 묶음 5회 모두 통과. 바쁜
  이웃 2개로 3회 돌렸을 때도 이 커밋이 다루는 테스트는 모두 통과했다.
  넓은 묶음 한 번의 시간은 RED 91~111s(실패가 몰린 209s 회차 제외)
  -> GREEN 86~88s다.
- 기본 코어: tests/unit·component·integration 212파일 2,734개, features·
  platform·architecture·contract·runtime-schema 60파일 403개 통과.
  tsc -p tsconfig.test.json, 바꾼 파일 eslint 통과.

Refs: docs/reviews/2026-09-29-maturity-review/10-tests-fast-layers.md
2026-11-01 21:23:10 +09:00

245 lines
8.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";
// 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"],
) {
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();
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("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(),
);
}
});
});