Files
clean-architecture-frontend…/tests/component/route-status-surfaces.test.tsx
T
DongHyeonka ca74caa2a8 test(component): 플랫폼 화면 테스트를 테스트 전용 페이지로 옮긴다 (0929/10-02)
문제: 라우터·chunk 복구·render 경계·앱 셸·런타임 트리 테스트가 스타터
화면(`/`의 h1, 홈의 "플랫폼 구성 보기" 링크, /examples/ui·states)을
대상으로 쓴다. 문서는 스타터 화면을 "페이지 단위로 교체 가능"하다고 하는데,
제품이 화면을 바꾸면 스타터와 무관한 플랫폼 테스트가 깨지고 동기화 때마다
같은 파일이 충돌한다(두 제품 기록).

방법: tests/helpers/fixture-feature.tsx에 테스트 전용 public 페이지 4개를
더했다. 메뉴에 나오는 지연 로드 페이지 2개(제목 h1, 런타임 릴리스 표시),
chunk 로드 실패 페이지, render 결함 페이지다. 플랫폼 테스트는 이미 쓰던
방식대로 생성 인덱스를 mock해 이 기능을 설치하고 그 페이지를 쓴다.
스타터 화면 자체를 검사하던 것(홈 시작 링크, 홈·플랫폼 구성의 릴리스 로딩
실패, 인증 예제의 복귀 URL, 상태 갤러리 제목 구조, 플랫폼 구성 화면)은
starter-pages.test.tsx와 starter-platform-overview-page.test.tsx로
모았다. 제품은 스타터 화면과 함께 starter-* 파일을 지우면 된다.
fixture는 design-system 배럴 대신 page-header.tsx를 직접 import한다.
배럴이 설치 카탈로그를 거쳐 mock된 생성 인덱스를 다시 불러 mock 팩토리가
자기 자신을 기다린다.
버린 대안: README에 "함께 사라지는 검사" 목록만 적는다. 비용은 0이지만
화면을 바꾸면 검사는 여전히 깨지거나 사라진다.

위험: 플랫폼 경로(createRegisteredRoutes의 platformChildren)를 지나는
화면 이동 테스트가 줄고 context 라우트 경로로 옮겨 갔다. `/`와 not-found는
여전히 플랫폼 경로로 돈다. ui-gallery-page는 이제 component 테스트에서
렌더되지 않는다(e2e·visual이 본다). sibling chunk 초기화 테스트는
key={definition.routeId}를 지우면 여전히 실패한다(변이 확인).

검증: RED는 템플릿 복사본에서 home-page.tsx와 examples/*를 다른 화면으로
바꾸고 test:component를 돌렸다. 7파일 20개 실패(router 5, route-status 4,
platform-overview 7, app-shell·async-surface·chunk-recovery·
runtime-application 각 1). GREEN은 같은 조작에서 starter-* 2파일 12개만
실패하고, starter-*를 지우면 34파일 216개 전부 통과. worktree에서
tests/component 36파일 228개 통과, tsc -p tsconfig.test.json 통과, 바꾼
파일 eslint 통과.
2026-11-03 01:18:21 +09:00

141 lines
5.4 KiB
TypeScript

// @vitest-environment jsdom
import { render, screen, waitFor, within } 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 { 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";
// Routes and pages come from a test-only feature, not the removable sample
// (FE-GATE-020 runs the suite 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 deferred() {
let reject: (error: unknown) => void = () => {};
const promise = new Promise<void>((_, fail) => {
reject = fail;
});
return { promise, reject };
}
function renderApp(
url: string,
overrides: Partial<ApplicationOutputPorts> = {},
basename?: string,
) {
window.history.pushState({}, "", url);
return render(
<ApplicationProvider application={createTestApplication(overrides)}>
<PreferenceProviders>
<AppRouter {...(basename ? { basename } : {})} />
</PreferenceProviders>
</ApplicationProvider>,
);
}
function sessionWithSignIn(beginSignIn: (returnTo?: string) => Promise<void>) {
return { ...createAnonymousSessionAdapter(), beginSignIn };
}
describe("route-level status surfaces", () => {
// First in the file: the page chunk has not been loaded yet, so the route
// suspends and shows its own loading surface (the context's routes load
// behind a surface without the route's name).
it("shows the busy route loading surface while a page chunk loads", async () => {
const { container } = renderApp("/fixture/first");
await waitFor(() =>
expect(
container.querySelector('.route-loading[data-surface="fixture-page"]'),
).not.toBeNull(),
);
const surface = container.querySelector<HTMLElement>(
'.route-loading[data-surface="fixture-page"]',
)!;
const copy = within(surface).getByText("화면을 준비하고 있습니다.");
expect(copy.closest('[aria-busy="true"]')).not.toBeNull();
expect(
await screen.findByRole(
"heading",
{ name: "Fixture first page", level: 1 },
),
).toBeVisible();
});
it("keeps the auth-required surface, its pending label and its failure alert", async () => {
const user = userEvent.setup();
const pending = deferred();
const beginSignIn = vi.fn(() => pending.promise);
const { container } = renderApp("/fixture/items#results", {
session: sessionWithSignIn(beginSignIn),
});
const heading = await screen.findByRole(
"heading",
{ name: "세션이 필요합니다.", level: 1 },
);
const surface = container.querySelector(
'[data-surface="authentication-required"]',
);
expect(surface).not.toBeNull();
expect(surface).toContainElement(heading);
await user.click(screen.getByRole("button", { name: "로그인 시작" }));
expect(beginSignIn).toHaveBeenCalledWith(
"/fixture/items#results",
);
expect(screen.getByRole("button", { name: "처리 중…" })).toBeDisabled();
pending.reject(new Error("identity provider unavailable"));
expect(await screen.findByRole("alert")).toHaveTextContent(
"세션 작업을 완료하지 못했습니다.",
);
expect(screen.getByRole("button", { name: "로그인 시작" })).toBeEnabled();
});
it("returns to the current URL with its hash from the shell session action", async () => {
const user = userEvent.setup();
const pending = deferred();
const beginSignIn = vi.fn(() => pending.promise);
renderApp("/fixture/first#buttons", { session: sessionWithSignIn(beginSignIn) });
const banner = screen.getByRole("banner");
await user.click(
await within(banner).findByRole("button", { name: "로그인" }),
);
expect(beginSignIn).toHaveBeenCalledWith("/fixture/first#buttons");
expect(within(banner).getByRole("button", { name: "처리 중…" })).toBeDisabled();
pending.reject(new Error("identity provider unavailable"));
expect(await within(banner).findByRole("alert")).toHaveTextContent(
"세션 작업을 완료하지 못했습니다.",
);
});
it("answers an unknown address with a home link that keeps the basename", async () => {
renderApp("/app/missing", {}, "/app");
const heading = await screen.findByRole(
"heading",
{ name: "페이지를 찾을 수 없습니다.", level: 1 },
);
const page = heading.closest("section");
expect(page).not.toBeNull();
expect(
within(page!).getByRole("link", { name: "홈으로 이동" }),
).toHaveAttribute("href", "/app");
});
});