Files
clean-architecture-frontend…/tests/component/render-boundary.test.tsx
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

220 lines
7.4 KiB
TypeScript

// @vitest-environment jsdom
import { render, screen } from "@testing-library/react";
import type { ReactNode } from "react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { createFailure } from "../../src/contracts/errors.ts";
import { deriveAsyncState } from "../../src/application/view-models/async-state.ts";
import { AsyncSurface } from "../../src/presentation/components/async-surface.tsx";
import { BootErrorShell } from "../../src/presentation/boundaries/boot-error-shell.tsx";
import { FeatureBoundary } from "../../src/presentation/boundaries/render-error-boundary.tsx";
import { LocaleProvider } from "../../src/presentation/i18n/index.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";
// The test-only feature's broken page stands in for any route page with a
// programmer defect; the starter screens are the product's to replace
// (0929/10-02).
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 Defect(): ReactNode {
throw new Error("raw render stack");
}
describe("render recovery boundaries", () => {
it("catches programmer defects and emits best-effort safe telemetry", () => {
const onRenderFailure = vi.fn();
render(
<FeatureBoundary
routeId="APP_HOME"
buildId="build-a"
onRenderFailure={onRenderFailure}
>
<Defect />
</FeatureBoundary>,
);
expect(screen.getByRole("alert")).toHaveTextContent(
"화면을 표시하지 못했습니다.",
);
expect(onRenderFailure).toHaveBeenCalledWith({
routeId: "APP_HOME",
buildId: "build-a",
boundaryName: "feature",
incidentId: expect.stringMatching(/^[0-9a-f]{8}$/),
});
});
// 08-07. The route failure page shows the reference the user quotes, the
// same id the render diagnostic records, and a way out besides the URL.
it("shows a route render failure's support reference and records it", async () => {
const record = vi.fn();
window.history.pushState({}, "", "/fixture/broken");
render(
<ApplicationProvider
application={createTestApplication({ diagnostics: { record } })}
>
<PreferenceProviders>
<AppRouter buildId="build-a" />
</PreferenceProviders>
</ApplicationProvider>,
);
const reference = await screen.findByText(/^지원 참조: build-a:[0-9a-f]{8}$/);
const incidentId = reference.textContent?.split(":").at(-1);
expect(record).toHaveBeenCalledWith({
level: "error",
eventId: "ui.render.failed",
context: expect.objectContaining({
route_id: "FIXTURE_BROKEN_PAGE",
build_id: "build-a",
correlation_id: incidentId,
}),
});
expect(screen.getByRole("button", { name: "한 번 새로고침" })).toBeVisible();
});
it("keeps normalized operational failures in normal async state", () => {
const state = deriveAsyncState({
failure: createFailure("SERVER_FAILURE", "LIST", 0),
});
render(
<FeatureBoundary routeId="APP_HOME" buildId="build-a">
<AsyncSurface state={state} />
</FeatureBoundary>,
);
expect(screen.getByRole("alert")).toHaveTextContent(
"요청을 완료하지 못했습니다.",
);
expect(screen.getByRole("alert")).toHaveAttribute(
"data-message-key",
"error.server_failure",
);
});
it("renders a safe boot shell with no endpoint or stack", () => {
render(
<BootErrorShell
kind="BOOT_CONFIG_FAILURE"
code="CONFIG_SCHEMA_INVALID"
buildId="build-a"
configSchemaVersion="1"
supportReference="build-a:CONFIG_SCHEMA_INVALID"
/>,
);
const shell = screen.getByRole("alert");
expect(shell).toHaveTextContent("build-a:CONFIG_SCHEMA_INVALID");
expect(shell).not.toHaveTextContent("https://");
expect(shell).not.toHaveTextContent("stack");
});
it.each(["CONFIG_FETCH_FAILED", "CONFIG_TIMEOUT", "MANIFEST_FETCH_FAILED", "MANIFEST_TIMEOUT"])(
"offers a retry for the network failure %s (09-10)",
async (code) => {
const onRetry = vi.fn();
const user = userEvent.setup();
render(
<BootErrorShell
kind="BOOT_CONFIG_FAILURE"
code={code}
supportReference={`build-a:${code}`}
onRetry={onRetry}
/>,
);
expect(screen.getByRole("alert")).toHaveTextContent(
"네트워크 연결을 확인한 뒤 다시 시도해 주세요.",
);
await user.click(screen.getByRole("button", { name: "다시 시도" }));
expect(onRetry).toHaveBeenCalledTimes(1);
},
);
it("offers no retry for a failure a reload cannot fix (09-10)", () => {
render(
<BootErrorShell
kind="BOOT_CONFIG_FAILURE"
code="CONFIG_SCHEMA_INVALID"
supportReference="build-a:CONFIG_SCHEMA_INVALID"
onRetry={() => {}}
/>,
);
expect(screen.queryByRole("button")).toBeNull();
});
it("allows a boundary reset action without reloading the page", async () => {
let shouldThrow = true;
function Recoverable() {
if (shouldThrow) throw new Error("defect");
return <p>recovered</p>;
}
const user = userEvent.setup();
const view = render(
<FeatureBoundary routeId="APP_HOME" buildId="build-a">
<Recoverable />
</FeatureBoundary>,
);
shouldThrow = false;
await user.click(screen.getByRole("button", { name: "다시 시도" }));
view.rerender(
<FeatureBoundary routeId="APP_HOME" buildId="build-a">
<Recoverable />
</FeatureBoundary>,
);
expect(screen.getByText("recovered")).toBeVisible();
});
it("resets a route failure when the registered location key changes", async () => {
let shouldThrow = true;
function RouteContent() {
if (shouldThrow) throw new Error("route defect");
return <p>next route</p>;
}
const view = render(
<FeatureBoundary
routeId="APP_HOME"
buildId="build-a"
resetKey="/first"
>
<RouteContent />
</FeatureBoundary>,
);
expect(screen.getByRole("alert")).toBeVisible();
shouldThrow = false;
view.rerender(
<FeatureBoundary
routeId="APP_HOME"
buildId="build-a"
resetKey="/second"
>
<RouteContent />
</FeatureBoundary>,
);
expect(await screen.findByText("next route")).toBeVisible();
});
it("renders the default fallback in the current locale", () => {
render(
<LocaleProvider initialLocale="en-US">
<FeatureBoundary routeId="APP_HOME" buildId="build-a">
<Defect />
</FeatureBoundary>
</LocaleProvider>,
);
expect(screen.getByRole("alert")).toHaveTextContent(
"The page could not be displayed.",
);
expect(screen.getByRole("button", { name: "Try again" })).toBeVisible();
});
});