Files
clean-architecture-frontend…/tests/component/async-surface.test.tsx
T
DongHyeonkaandClaude Opus 5.5 5848493580 fix(presentation): show a disabled query as idle instead of empty (R3-4)
A disabled query (no data, no error, not fetching) fell through
deriveAsyncState to "empty", so AsyncSurface rendered the
"no items" copy before the query had even started.

- AsyncState.base gains "idle" for "not started / waiting on a
  precondition". A completed empty result (`[]`, `""`, `null`) stays
  "empty"; a real first load stays "initial-loading".
- AsyncSurface renders an optional `idle` slot for idle, else nothing
  (no skeleton, no aria-busy, no empty copy, no children).

Consumer-facing: AsyncState["base"] union adds "idle" (additive);
AsyncSurface gains an optional `idle` prop. No in-repo exhaustive
switch over base needed changes.

RED (before the fix, node scripts/run-vitest.ts on the two files):
  application-query-bridge > disabled query: expected 'empty' to be 'idle'
  async-surface > derives base state 4 ({}): expected 'empty' to be 'idle'
  async-surface > idle renders neither loading nor empty:
    toBeEmptyDOMElement() received the empty-copy section
  Tests 3 failed | 25 passed (pins for first load, [] and null empty passed)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 15:14:11 +09:00

230 lines
7.5 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";
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 reconciliation-only actions", async () => {
const user = userEvent.setup();
const retry = vi.fn();
const reconcile = vi.fn();
const state = deriveAsyncState({
data: ["value"],
hasMutationEffectUnknown: true,
});
render(
<AsyncSurface
state={state}
onRetry={retry}
onReconcileUnknownEffect={reconcile}
>
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();
await user.click(screen.getByRole("button", { name: "변경됨으로 확인" }));
await user.click(
screen.getByRole("button", { name: "변경되지 않음으로 확인" }),
);
expect(reconcile).toHaveBeenNthCalledWith(1, "APPLIED");
expect(reconcile).toHaveBeenNthCalledWith(2, "NOT_APPLIED");
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();
});
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();
});
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();
});
});