문제: EmptySurface, TerminalErrorSurface, 접근 상태 화면, ErrorSummary의 제목이 h2로 고정돼 있다. Card(h3)나 상세 구획(h2) 안에 넣으면 그 안의 상태 문구가 카드 제목보다 상위 제목이 된다. /examples/states에서 h3 카드 안에 h2가 있었고, 섹션 h2 아래 접근 상태 화면도 h2였다. 상태 화면 제목을 <p>로 바꾸는 변이(M5)를 잡는 테스트도 없었다. 고른 방법: Card에 이미 있는 계약을 그대로 옮겼다. 위 네 컴포넌트에 headingLevel?: 2 | 3 | 4(기본 2)를 더하고, 이들을 그리는 AsyncSurface와 AccessSurface가 같은 prop을 넘긴다(그러지 않으면 가장 흔한 진입점에서 뒤집힘이 남는다). 타입은 state-surfaces.tsx의 HeadingLevel 하나에 둔다. 갤러리는 카드 안 상태에 4, 섹션 바로 아래 접근 상태에 3을 준다. 상태·오류 요약 CSS 선택자는 :is(h2, h3, h4)로 넓혔다. 공개 prop은 추가만 했고 기본값이 그대로라 기존 화면은 바뀌지 않는다. 버린 대안: 제목 수준 context(R7) — 모든 컨테이너가 제공자를 둬야 하고 Card의 prop 계약과 갈린다. Card의 인라인 2 | 3 | 4와 HeadingLevel을 합치는 것은 VD-05 재수출 경로를 건드려 이번 범위에서 뺐다. 위험·한계: 갤러리 화면이 바뀐다(카드 안 상태 제목 h4 16px, 접근 상태 h3 20px). 시각 골든은 오케스트레이터가 갱신한다. 실제 스크린 리더 제목 목록은 확인하지 않았다(접근성 트리 대신 component 단언). 검증: - RED: async-surface.test.tsx 새 테스트 7건이 수정 전 실패(예: "expected [ <h2></h2> ] to have a length of +0 but got 1"). - GREEN: async-surface.test.tsx 31/31, tests/component 220/220(4회 반복 통과, 부하 32에서 첫 실행 1건 실패 뒤 재현 안 됨). tsc app·test 통과, eslint 통과. e2e accessibility·typography·reference-form·reference-save chromium 27/27. Refs: docs/reviews/2026-11-01-maturity-review/08-presentation.md 08-05
361 lines
12 KiB
TypeScript
361 lines
12 KiB
TypeScript
// @vitest-environment jsdom
|
|
|
|
import { render, screen } from "@testing-library/react";
|
|
import userEvent from "@testing-library/user-event";
|
|
import { describe, expect, it, vi } from "vitest";
|
|
|
|
import { deriveAsyncState } from "../../src/application/view-models/async-state.ts";
|
|
import { AsyncSurface } from "../../src/presentation/components/async-surface.tsx";
|
|
import { createFailure } from "../../src/contracts/errors.ts";
|
|
import {
|
|
AccessSurface,
|
|
EmptySurface,
|
|
ErrorSummary,
|
|
TerminalErrorSurface,
|
|
} from "../../src/presentation/design-system/index.ts";
|
|
import StateGalleryPage from "../../src/presentation/examples/state-gallery-page.tsx";
|
|
|
|
describe("async UI state matrix", () => {
|
|
it.each([
|
|
[{ isInitialLoading: true }, "initial-loading"],
|
|
[{ data: [{ id: "1" }] }, "success"],
|
|
[{ data: [] }, "empty"],
|
|
[{ data: null }, "empty"],
|
|
[{}, "idle"],
|
|
[
|
|
{ failure: createFailure("SERVER_FAILURE", "LIST", 0) },
|
|
"terminal-error",
|
|
],
|
|
])("derives base state %#", (signals, expected) => {
|
|
expect(deriveAsyncState(signals).base).toBe(expected);
|
|
});
|
|
|
|
it.each([
|
|
[{ data: ["value"], isFetching: true }, "refreshing"],
|
|
[{ data: ["value"], isStale: true, isDegraded: true }, "stale-degraded"],
|
|
[{ data: ["value"], isMutationPending: true }, "mutation-pending"],
|
|
[
|
|
{ data: ["value"], hasMutationEffectUnknown: true },
|
|
"mutation-effect-unknown",
|
|
],
|
|
[{ data: ["value"], hasMutationConflict: true }, "mutation-conflict"],
|
|
])("derives overlay state %#", (signals, indicator) => {
|
|
expect(deriveAsyncState(signals).indicator).toBe(indicator);
|
|
});
|
|
|
|
it("makes crossed overlay inputs mutually exclusive by priority", () => {
|
|
const state = deriveAsyncState({
|
|
data: ["value"],
|
|
isFetching: true,
|
|
isMutationPending: true,
|
|
hasMutationEffectUnknown: true,
|
|
hasMutationConflict: true,
|
|
});
|
|
expect(state.indicator).toBe("mutation-effect-unknown");
|
|
expect(state.overlay).toMatchObject({
|
|
refreshing: false,
|
|
mutationPending: false,
|
|
mutationEffectUnknown: true,
|
|
mutationConflict: false,
|
|
});
|
|
});
|
|
|
|
it("renders unknown mutation effects with confirm-applied and resend only", async () => {
|
|
const user = userEvent.setup();
|
|
const retry = vi.fn();
|
|
const reconcile = vi.fn();
|
|
const resend = vi.fn();
|
|
const state = deriveAsyncState({
|
|
data: ["value"],
|
|
hasMutationEffectUnknown: true,
|
|
});
|
|
|
|
render(
|
|
<AsyncSurface
|
|
state={state}
|
|
onRetry={retry}
|
|
onReconcileUnknownEffect={reconcile}
|
|
onResendUnknownEffect={resend}
|
|
>
|
|
existing content
|
|
</AsyncSurface>,
|
|
);
|
|
|
|
expect(screen.getByRole("status")).toHaveTextContent(
|
|
"변경 결과를 확인할 수 없습니다.",
|
|
);
|
|
expect(
|
|
screen.getByText("existing content").closest("section"),
|
|
).toHaveAttribute("aria-busy", "false");
|
|
expect(
|
|
screen.queryByRole("button", { name: "다시 시도" }),
|
|
).not.toBeInTheDocument();
|
|
expect(
|
|
screen.queryByRole("button", { name: "변경되지 않음으로 확인" }),
|
|
).not.toBeInTheDocument();
|
|
await user.click(screen.getByRole("button", { name: "변경됨으로 확인" }));
|
|
await user.click(
|
|
screen.getByRole("button", { name: "같은 요청으로 다시 보내기" }),
|
|
);
|
|
expect(reconcile).toHaveBeenCalledExactlyOnceWith("APPLIED");
|
|
expect(resend).toHaveBeenCalledOnce();
|
|
expect(retry).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("keeps content visible while a non-blocking refresh runs", () => {
|
|
const state = deriveAsyncState({ data: ["value"], isFetching: true });
|
|
render(<AsyncSurface state={state}>existing content</AsyncSurface>);
|
|
|
|
expect(screen.getByText("existing content")).toBeVisible();
|
|
expect(screen.getByRole("status")).toHaveTextContent(
|
|
"최신 정보를 확인하고 있습니다.",
|
|
);
|
|
});
|
|
|
|
it("connects stale retry and conflict resolution to real callbacks", async () => {
|
|
const user = userEvent.setup();
|
|
const retry = vi.fn();
|
|
const resolveConflict = vi.fn();
|
|
const stale = deriveAsyncState({
|
|
data: ["value"],
|
|
isStale: true,
|
|
isDegraded: true,
|
|
});
|
|
const view = render(
|
|
<AsyncSurface state={stale} onRetry={retry}>
|
|
existing content
|
|
</AsyncSurface>,
|
|
);
|
|
await user.click(screen.getByRole("button", { name: "다시 시도" }));
|
|
expect(retry).toHaveBeenCalledOnce();
|
|
|
|
const conflict = deriveAsyncState({
|
|
data: ["value"],
|
|
hasMutationConflict: true,
|
|
});
|
|
view.rerender(
|
|
<AsyncSurface
|
|
state={conflict}
|
|
onResolveConflict={resolveConflict}
|
|
>
|
|
existing content
|
|
</AsyncSurface>,
|
|
);
|
|
await user.click(screen.getByRole("button", { name: "충돌 해결" }));
|
|
expect(resolveConflict).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
// 08-07. The id a user quotes when asking for help is the one the request
|
|
// diagnostics carry as `correlation_id`.
|
|
it("shows the failure's request id as its support reference", () => {
|
|
const failure = {
|
|
...createFailure("SERVER_FAILURE", "LIST", 1),
|
|
requestId: "req-7f3a",
|
|
};
|
|
render(<AsyncSurface state={deriveAsyncState({ failure })} />);
|
|
expect(screen.getByRole("alert")).toHaveTextContent("지원 참조: req-7f3a");
|
|
});
|
|
|
|
it("renders only safe error vocabulary", () => {
|
|
const failure = createFailure("SERVER_FAILURE", "LIST", 0, {
|
|
code: "SERVER_FAILURE",
|
|
});
|
|
const state = deriveAsyncState({ failure });
|
|
render(<AsyncSurface state={state} onRetry={vi.fn()} />);
|
|
|
|
expect(screen.getByRole("alert")).toHaveTextContent(
|
|
"요청을 완료하지 못했습니다.",
|
|
);
|
|
expect(screen.getByRole("alert")).toHaveAttribute(
|
|
"data-message-key",
|
|
failure.userMessageKey,
|
|
);
|
|
expect(screen.getByRole("button")).toHaveTextContent("다시 시도");
|
|
expect(screen.getByRole("alert")).not.toHaveTextContent("stack");
|
|
});
|
|
|
|
it("routes terminal actions by failure semantics", async () => {
|
|
const user = userEvent.setup();
|
|
const retry = vi.fn();
|
|
const action = vi.fn();
|
|
const forbidden = deriveAsyncState({
|
|
failure: createFailure("FORBIDDEN", "LIST", 0),
|
|
});
|
|
const view = render(
|
|
<AsyncSurface
|
|
state={forbidden}
|
|
onAction={action}
|
|
onRetry={retry}
|
|
/>,
|
|
);
|
|
|
|
await user.click(
|
|
screen.getByRole("button", { name: "안전한 화면으로 이동" }),
|
|
);
|
|
expect(action).toHaveBeenCalledOnce();
|
|
expect(retry).not.toHaveBeenCalled();
|
|
|
|
const retryable = deriveAsyncState({
|
|
failure: createFailure("SERVER_FAILURE", "LIST", 0),
|
|
});
|
|
view.rerender(
|
|
<AsyncSurface
|
|
state={retryable}
|
|
onAction={action}
|
|
onRetry={retry}
|
|
/>,
|
|
);
|
|
await user.click(screen.getByRole("button", { name: "다시 시도" }));
|
|
expect(retry).toHaveBeenCalledOnce();
|
|
expect(action).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it("renders an idle query as neither loading nor empty", () => {
|
|
const { container, rerender } = render(
|
|
<AsyncSurface state={deriveAsyncState({})}>content</AsyncSurface>,
|
|
);
|
|
expect(container).toBeEmptyDOMElement();
|
|
|
|
rerender(
|
|
<AsyncSurface
|
|
state={deriveAsyncState({})}
|
|
idle={<p>조건을 먼저 선택하세요.</p>}
|
|
>
|
|
content
|
|
</AsyncSurface>,
|
|
);
|
|
expect(screen.getByText("조건을 먼저 선택하세요.")).toBeVisible();
|
|
expect(container.querySelector("[aria-busy]")).toBeNull();
|
|
expect(screen.queryByText("표시할 항목이 없습니다.")).toBeNull();
|
|
expect(screen.queryByText("content")).toBeNull();
|
|
});
|
|
|
|
it("still renders loading for a first load and the empty copy for an empty result", () => {
|
|
const { container, rerender } = render(
|
|
<AsyncSurface state={deriveAsyncState({ isInitialLoading: true })} />,
|
|
);
|
|
expect(container.querySelector('[aria-busy="true"]')).not.toBeNull();
|
|
|
|
rerender(<AsyncSurface state={deriveAsyncState({ data: [] })} />);
|
|
expect(screen.getByText("표시할 항목이 없습니다.")).toBeVisible();
|
|
});
|
|
|
|
// 08-11. A query failure and the gallery draw one access set, not two.
|
|
it.each([
|
|
["AUTH_REQUIRED", "auth-required"],
|
|
["FORBIDDEN", "forbidden"],
|
|
["NOT_FOUND", "not-found"],
|
|
] as const)(
|
|
"renders a %s query failure with the gallery's access surface",
|
|
async (kind, accessKind) => {
|
|
const user = userEvent.setup();
|
|
const action = vi.fn();
|
|
const failure = createFailure(kind, "LIST", 0);
|
|
const gallery = render(
|
|
<AccessSurface kind={accessKind} onAction={() => {}} />,
|
|
);
|
|
const expected = gallery.container.querySelector(".state-surface");
|
|
expect(expected).not.toBeNull();
|
|
const expectedText = expected?.textContent;
|
|
gallery.unmount();
|
|
|
|
render(
|
|
<AsyncSurface
|
|
state={deriveAsyncState({ failure })}
|
|
onAction={action}
|
|
/>,
|
|
);
|
|
const alert = screen.getByRole("alert");
|
|
expect(alert).toHaveAttribute("data-message-key", failure.userMessageKey);
|
|
expect(alert.querySelector(".state-surface")?.textContent).toBe(
|
|
expectedText,
|
|
);
|
|
await user.click(screen.getByRole("button"));
|
|
expect(action).toHaveBeenCalledOnce();
|
|
},
|
|
);
|
|
|
|
it("does not retain a terminal error after usable data is restored", () => {
|
|
const failed = deriveAsyncState({
|
|
failure: createFailure("SERVER_FAILURE", "LIST", 0),
|
|
});
|
|
const recovered = deriveAsyncState({ data: ["value"] });
|
|
expect(failed.base).toBe("terminal-error");
|
|
expect(recovered.base).toBe("success");
|
|
expect(recovered.failure).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
describe("state surface titles (08-05)", () => {
|
|
const forbidden = createFailure("FORBIDDEN", "LIST", 0);
|
|
const unreachable = createFailure("NETWORK_UNREACHABLE", "LIST", 0);
|
|
|
|
it.each([
|
|
["empty", (level?: 2 | 3 | 4) => <EmptySurface title="빈 목록" headingLevel={level} />],
|
|
[
|
|
"terminal error",
|
|
(level?: 2 | 3 | 4) => (
|
|
<TerminalErrorSurface
|
|
userMessageKey={unreachable.userMessageKey}
|
|
action="none"
|
|
headingLevel={level}
|
|
/>
|
|
),
|
|
],
|
|
[
|
|
"access",
|
|
(level?: 2 | 3 | 4) => (
|
|
<AccessSurface kind="forbidden" onAction={() => {}} headingLevel={level} />
|
|
),
|
|
],
|
|
[
|
|
"async empty",
|
|
(level?: 2 | 3 | 4) => (
|
|
<AsyncSurface state={deriveAsyncState({ data: [] })} headingLevel={level} />
|
|
),
|
|
],
|
|
[
|
|
"async access failure",
|
|
(level?: 2 | 3 | 4) => (
|
|
<AsyncSurface
|
|
state={deriveAsyncState({ failure: forbidden })}
|
|
headingLevel={level}
|
|
/>
|
|
),
|
|
],
|
|
[
|
|
"form error summary",
|
|
(level?: 2 | 3 | 4) => (
|
|
<ErrorSummary
|
|
fieldErrors={{ name: "이름을 입력해 주세요." }}
|
|
fieldLabels={{ name: "이름" }}
|
|
fieldId={(name) => name}
|
|
headingLevel={level}
|
|
/>
|
|
),
|
|
],
|
|
])("titles the %s surface as h2 unless placed deeper", (_, surface) => {
|
|
const { unmount } = render(surface());
|
|
expect(screen.getAllByRole("heading", { level: 2 })).toHaveLength(1);
|
|
unmount();
|
|
|
|
render(surface(4));
|
|
expect(screen.queryAllByRole("heading", { level: 2 })).toHaveLength(0);
|
|
expect(screen.getAllByRole("heading", { level: 4 })).toHaveLength(1);
|
|
});
|
|
|
|
it("nests the gallery's state titles under the card and section around them", () => {
|
|
render(<StateGalleryPage />);
|
|
|
|
expect(
|
|
screen.getByRole("heading", { name: "아직 표시할 항목이 없습니다.", level: 4 }),
|
|
).toBeVisible();
|
|
expect(screen.getAllByRole("heading", { level: 3 }).map((h) => h.textContent))
|
|
.toEqual(expect.arrayContaining(["빈 화면", "복구 가능한 오류"]));
|
|
// Access states sit directly under the section's h2.
|
|
expect(
|
|
screen.queryAllByRole("heading", { level: 2 }).map((h) => h.textContent),
|
|
).toEqual(["비동기 데이터 상태", "접근과 탐색 상태"]);
|
|
});
|
|
});
|