Files
clean-architecture-frontend…/tests/component/async-surface.test.tsx
T
DongHyeonka 683ccfb56b fix(query): 키 없는 결과 불명 요청의 같은 입력 재제출을 훅이 막는다
문제
0929/03-03은 화면 버튼 쪽만 고쳐졌다. 남은 길이 둘이다.
- useApplicationMutation의 submit은 같은 canonical input의 결과 불명
  admission을 찾아 그 intent를 그대로 다시 보낸다. 키 없는 intent(NEVER)면
  서버가 가려낼 수 없는 두 번째 요청이다. 막는 곳은 폼(unknownSubmissionRef)과
  두 페이지의 버튼·onSubmit 검사뿐이라, 폼 밖에서 submit을 부르는 화면은 같은
  항목을 둘 만들 수 있다(리뷰 실험 X1: 재전송은 null인데 같은 입력 submit이
  두 번째 POST를 보냈고 keys=[null,null]).
- AsyncSurface는 state.unknownEffectResendable !== false일 때 재전송 버튼을
  그린다. 코디네이터 없이 손으로 만든 AsyncState(플래그 없음)는 지금도 버튼을
  그린다(실험 X3).

고른 방법
- submit이 같은 입력의 결과 불명 admission을 찾았는데 그 intent에 키가 없으면
  보내지 않고 NOT_STARTED DUPLICATE_IN_FLIGHT(code UNKNOWN_EFFECT_PENDING)를
  돌려준다. admission을 만들기 전이라 결과 불명 상태와 identity lease는 그대로다.
  KEYED의 같은 키 재전송, 입력이 바뀐 새 요청은 바뀌지 않는다. LEGACY(테스트
  하네스) 경로는 intent가 없어 replay 자체가 없으므로 영향이 없다.
- AsyncSurface는 unknownEffectResendable === true일 때만 재전송 버튼을 그린다.
  코디네이터의 state는 늘 이 값을 싣는다(canResendUnknownEffect).
- 기존 async-surface 테스트 "renders unknown mutation effects with
  confirm-applied and resend only"는 플래그 없는 상태로 버튼을 기대했다. 이
  수정의 의도대로 isUnknownEffectResendable: true를 입력에 적었다. 단언은 그대로다.
- 런북 6.3-4와 매뉴얼 01에 키 없는 재제출과 손으로 만든 상태를 적었다.

버린 대안
FailureKind에 새 kind를 더한다: 닫힌 레지스트리를 넓히는 계약 변경이다.
"같은 논리 요청이 아직 끝나지 않았다"는 DUPLICATE_IN_FLIGHT(action none)로
충분하다.

위험·한계
- 다운스트림이 AsyncSurface에 손으로 만든 결과 불명 상태와 onResendUnknownEffect를
  넘기던 화면은 재전송 버튼이 사라진다. 코디네이터의 state를 넘기면 그대로다.
- 결과 불명 admission은 메모리에만 있다. 새로고침 뒤 같은 입력은 막지 못한다
  (런북 6.3-7의 한계 그대로).

검증
desktop batch에서 확인:
node scripts/run-vitest.ts run tests/component/application-mutation-admission.test.tsx
tests/component/async-surface.test.tsx tests/component/application-query.test.tsx

Refs: 0929/03-03
2026-11-06 02:33:16 +09:00

420 lines
14 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,
LoadingSurface,
TerminalErrorSurface,
} from "../../src/presentation/design-system/index.ts";
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();
// 0929/03-03. The coordinator says the request carries a key.
const state = deriveAsyncState({
data: ["value"],
hasMutationEffectUnknown: true,
isUnknownEffectResendable: 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();
});
// 0929/03-03. The coordinator says when the unknown request has no key;
// the surface then draws no resend, whatever callback the page passes.
it("draws no resend for an unknown request that cannot be resent", () => {
render(
<AsyncSurface
state={deriveAsyncState({
data: ["value"],
hasMutationEffectUnknown: true,
isUnknownEffectResendable: false,
})}
onReconcileUnknownEffect={vi.fn()}
onResendUnknownEffect={vi.fn()}
/>,
);
expect(
screen.queryByRole("button", { name: "같은 요청으로 다시 보내기" }),
).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "변경됨으로 확인" })).toBeInTheDocument();
});
// 0929/03-03. A state built by hand without the coordinator's answer does
// not know the request has a key, so it draws no resend (review X3).
it("draws no resend for an unknown state that does not say it can be resent", () => {
render(
<AsyncSurface
state={deriveAsyncState({ data: ["value"], hasMutationEffectUnknown: true })}
onReconcileUnknownEffect={vi.fn()}
onResendUnknownEffect={vi.fn()}
/>,
);
expect(
screen.queryByRole("button", { name: "같은 요청으로 다시 보내기" }),
).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "변경됨으로 확인" })).toBeInTheDocument();
});
it("keeps the resend state to an unknown mutation only", () => {
expect(
deriveAsyncState({ data: ["value"], isUnknownEffectResendable: false }),
).not.toHaveProperty("unknownEffectResendable");
expect(
deriveAsyncState({
data: ["value"],
hasMutationEffectUnknown: true,
isUnknownEffectResendable: true,
}).unknownEffectResendable,
).toBe(true);
});
// 0929/08-04. The unknown result is the case a user most wants to report.
it("shows the support reference of a save whose effect is unknown", () => {
render(
<AsyncSurface
state={deriveAsyncState({ data: ["value"], hasMutationEffectUnknown: true })}
supportReference="corr-save-500"
/>,
);
expect(screen.getByRole("status")).toHaveTextContent("지원 참조: corr-save-500");
});
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("announces a loading surface politely while it is busy (08-09)", () => {
render(<LoadingSurface label="목록을 불러오는 중" />);
const surface = screen.getByRole("region", { name: "목록을 불러오는 중" });
expect(surface).toHaveAttribute("aria-busy", "true");
expect(surface).toHaveAttribute("aria-live", "polite");
});
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);
});
});