Files
clean-architecture-frontend…/tests/component/form-foundation.test.tsx
T
DongHyeonka 048f490ada refactor(http)!: V2 HTTP 클라이언트를 지우고 V3 실행기 하나만 남긴다
문제
HTTP 실행 경로가 둘이다. V3 실행기(createContractHttpExecutor)가 모든 기능을
실행하고, V2 클라이언트(createHttpClient)는 bootstrap의
createRuntimeHttpClient에서만 만들어지는데 그 함수를 앱 안에서 부르는 곳이
없다(테스트만 부른다). tech-log·memento도 같다. 그런데도 V2는 초기 청크에
들어가고, 짝 백엔드 해석(7db32e1~3261208)과 테스트를 두 벌로 유지하게 했다.
사용자 지시: 레거시를 두지 말고 최신 경로 하나만 남긴다.

고른 방법
- src/adapters/http/의 client.ts, bounded-json.ts, request-builder.ts,
  resource-mapper.ts, retry-policy.ts, schema-registry.ts를 지웠다. Envelope
  스키마는 backend-envelope.ts로 옮겼다. V3가 retry-policy.ts에서 쓰던
  parseRetryAfter는 그것이 감싸던 platform/retry-after.ts의
  parseRetryAfterDelay를 직접 부른다.
- 배럴의 V2 export와 bootstrap의 createRuntimeHttpClient·RuntimeHttpContract를
  지웠다.
- V2 전용 테스트(http-client, http-diagnostics, auth-recovery,
  legacy-http-credential-authority, bounded-json-compatibility,
  request-builder, retry-policy)와 tests/helpers/http-contract-fixture.ts를
  지웠다. 섞인 파일(http-execution-contract, runtime-adapters,
  boundary-mapper)은 V2 블록만 지웠다.
- V2로 돌던 폼 테스트(form-foundation)는 Envelope을 읽는 V3 keyed create
  계약으로 옮겼다. 400 VALIDATION_FAILED 필드 오류, {cause} 뒤 다시 저장,
  422 뒤 저장 꺼짐을 그대로 검사한다. http-execution-v3-envelope 테스트는 V2와
  비교하던 행을 기대 판정을 직접 적는 행으로 바꿨다.
- drill:runbook FE-RB-003은 V2 shouldRetry 대신 V3 실행기를 실제로 돌려
  보낸 요청 수를 센다(NEVER 503: 1회, SAFE 503: 재시도, SAFE 스키마 불일치:
  1회).
- check:diagnostics의 http 이벤트 생산자, registry-governance의 오류 표 소비자,
  risk-coverage 고위험 경로, 아키텍처 금지 fixture, adapter INVENTORY, 문서의
  경로를 V3 파일로 바꿨다.

버린 대안
- V2를 @deprecated로 한 릴리스 남기기: 템플릿과 두 다운스트림 모두 부르는
  곳이 없어 옮겨 갈 사용자가 없다. 남기면 초기 JS와 두 벌 유지 비용만 남는다.

위험·한계
- BREAKING: 배럴과 bootstrap의 V2 이름을 쓰던 제품 코드는 컴파일이 깨진다.
  CHANGELOG에 옮기는 방법을 적었다.
- V2에만 있던 동작이 사라졌다: 401 뒤 세션 복구 후 한 번 재전송, KEYED 503
  자동 재시도. V3는 401을 UNAUTHENTICATED로 넘기고 KEYED 요청은 보낸 뒤
  재시도하지 않는다.
- 기능마다 적는 V2 API 행(*-api-contract.ts, check:registries가 읽음)은 이
  커밋에서 지우지 않았다. 다음 커밋이 지운다.

검증
- check:types, lint, check:architecture(금지 fixture 9건 거절),
  check:adapter-inventory(140 files), check:diagnostics, check:registries,
  check:ci, verify:documentation 통과.
- test:unit 2,585, test:integration 114, test:component 245, test:contract 23,
  test:runtime-schema 56, tests/features 101 통과.
- drill:runbook FE-RB-003: no local check failed.
- check:bundle 통과. 초기 JS 203,354 → 201,598 B(−1,756 B).

BREAKING CHANGE: src/adapters/http/index.ts가 createHttpClient, HttpClient,
HttpClientDependencies, HttpFailure, HttpResult, LegacyHttpInput, Scheduler,
OperationRequestInput를, src/bootstrap/runtime-adapters.ts가
createRuntimeHttpClient, RuntimeHttpContract를 내보내지 않는다. 그 operation의
V3 descriptor를 만들어 createFeatureHttpBinding으로 실행한다.
2026-11-03 21:12:34 +09:00

827 lines
29 KiB
TypeScript

// @vitest-environment jsdom
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useState } from "react";
import { createMemoryRouter, RouterProvider, useNavigate } from "react-router-dom";
import { z } from "zod";
import { describe, expect, it, vi } from "vitest";
import {
createContractHttpExecutor,
createFeatureHttpBinding,
defineFeatureHttpOperation,
} from "../../src/adapters/http/index.ts";
import { mappingSuccess } from "../../src/contracts/boundary-mapper.ts";
import { createFailure } from "../../src/contracts/errors.ts";
import { createRuntimeIdentityRegistry } from "../../src/contracts/query-keys.ts";
import { zodValidator } from "../../src/contracts/zod-validator.ts";
import { useApplicationMutation } from "../../src/presentation/adapters/query/application-query.ts";
import { queryClient, scopeSnapshot, wrapper } from "./application-query-fixture.tsx";
import { Button } from "../../src/presentation/components/ui/button.ts";
import {
DirtyNavigationDialog,
ErrorSummary,
Form,
FormFailureStatus,
FormField,
useAppForm,
useDirtyNavigationGuard,
} from "../../src/presentation/forms/index.ts";
/**
* A keyed create that reads the paired backend's Envelope, the shape
* `create:feature` generates for a command.
*/
const FORM_CREATE_CONTRACT = Object.freeze({
contract: Object.freeze({
operationId: "FORM_CREATE_ENTITY",
method: "POST" as const,
pathTemplate: "/api/form-entities",
inputValidator: zodValidator(
"FormCreateEntityCommand",
z.object({ name: z.string().min(1) }).strict(),
),
outputValidator: zodValidator(
"FormEntity",
z.object({ id: z.string(), name: z.string() }).strip(),
),
problemValidator: zodValidator(
"FormProblem",
z
.object({
code: z.string().regex(/^[A-Z0-9_]{1,64}$/u),
details: z.unknown().optional(),
})
.strip(),
),
acceptedStatuses: Object.freeze([200]),
emptyBodyStatuses: Object.freeze([]),
retrySemantics: "KEYED" as const,
requestBody: "JSON" as const,
responseBody: "REQUIRED_JSON" as const,
responseEnvelope: "ENVELOPE_V1" as const,
commandRecovery: Object.freeze({
mode: "IDEMPOTENCY_REPLAY" as const,
operationIdentityField: "idempotencyKey",
}),
commandEffect: Object.freeze({
successEffect: "APPLIED_CONFIRMED" as const,
classifyProblem: () => "MAYBE_APPLIED" as const,
}),
projectRequest: (input: Readonly<{ name: string }>) =>
Object.freeze({
pathValues: Object.freeze({}),
queryEntries: Object.freeze([]),
body: Object.freeze({ ...input }),
}),
}),
frontend: Object.freeze({
policyId: "FORM_CREATE_V1",
requestByteLimit: 1_024,
responseByteLimit: 4_096,
totalDeadlineMs: 5_000,
retryBudget: 0 as const,
authProfileId: "ANONYMOUS",
diagnosticsOperation: "form.create",
}),
});
const FORM_OPERATIONS = Object.freeze({
FORM_CREATE_ENTITY: defineFeatureHttpOperation({
contract: FORM_CREATE_CONTRACT,
routeId: "FORM_ROUTE",
mapSuccess: (value) => mappingSuccess(value),
}),
});
function formBinding(fetcher: typeof fetch) {
const executor = createContractHttpExecutor({
baseUrl: "https://api.test",
maxRetryAttempts: 0,
attachCredentials: () => ({ kind: "READY" as const, headers: {} }),
fetcher,
});
return createFeatureHttpBinding(
Object.freeze({
execute: (contract, input, context) =>
executor.execute(contract, input, {
routeId: context.routeId,
scope: scopeSnapshot(),
...(context.intent === undefined ? {} : { intent: context.intent }),
}),
}),
FORM_OPERATIONS,
);
}
type Values = Readonly<Record<"name" | "note", string>>;
const schema = z
.object({
name: z.string().trim().min(2),
note: z.string().trim().default(""),
})
.strict();
const defaults: Values = { name: "", note: "" };
function FormHarness(props: Readonly<{
submit(command: Readonly<{ name: string; note?: string }>): Promise<
| Readonly<{ ok: true; value: string }>
| Readonly<{ ok: false; error: ReturnType<typeof createFailure> }>
>;
resetOnSuccess?: boolean;
onFailureAction?(): void;
}>) {
const form = useAppForm({
schema,
defaultValues: defaults,
allowedServerFields: ["name", "note"],
mapToCommand(values) {
return {
name: values.name,
...(values.note ? { note: values.note } : {}),
};
},
submit: props.submit,
resetOnSuccess: props.resetOnSuccess,
});
return (
<Form pending={form.pending} onSubmit={(event) => void form.submitForm(event)}>
<ErrorSummary
fieldErrors={form.fieldErrors}
formErrors={form.formErrors}
fieldLabels={{ name: "Name", note: "Note" }}
fieldId={form.fieldId}
onFocusField={form.focusField}
/>
<FormFailureStatus
failure={form.failure}
onAction={
form.result === "retry-later"
? () => void form.submitForm()
: props.onFailureAction
}
/>
<FormField {...form.field("name")} label="Name" required />
<FormField {...form.field("note")} label="Note" />
<Button type="submit" disabled={form.pending}>
{form.pending ? "Pending" : "Submit"}
</Button>
<Button onClick={() => form.reset()} disabled={!form.dirty}>
Reset
</Button>
<Button onClick={() => form.settleApplied()}>Confirm applied</Button>
<Button onClick={() => form.settleNotApplied()}>
Confirm not applied
</Button>
<output data-testid="dirty">{String(form.dirty)}</output>
<output data-testid="result">{form.result}</output>
<output data-testid="support">{form.supportReference ?? ""}</output>
</Form>
);
}
describe("local form facade", () => {
it("focuses the first invalid field and performs no command", async () => {
const user = userEvent.setup();
const submit = vi.fn();
render(<FormHarness submit={submit} />);
await user.click(screen.getByRole("button", { name: "Submit" }));
expect(submit).not.toHaveBeenCalled();
expect(screen.getByRole("textbox", { name: /Name/ })).toHaveFocus();
expect(screen.getByRole("alert")).toHaveTextContent("Name");
});
it("submits transformed data once and clears dirty state after success", async () => {
const user = userEvent.setup();
let finish: ((value: { ok: true; value: string }) => void) | undefined;
const submit = vi.fn(
() =>
new Promise<{ ok: true; value: string }>((resolve) => {
finish = resolve;
}),
);
render(<FormHarness submit={submit} />);
await user.type(screen.getByRole("textbox", { name: /Name/ }), " Ready ");
await user.type(screen.getByRole("textbox", { name: "Note" }), " Safe ");
await user.dblClick(screen.getByRole("button", { name: "Submit" }));
await waitFor(() => expect(submit).toHaveBeenCalledOnce());
expect(submit).toHaveBeenCalledWith({ name: "Ready", note: "Safe" });
expect(screen.getByRole("button", { name: "Pending" })).toBeDisabled();
finish?.({ ok: true, value: "saved" });
await waitFor(() => expect(screen.getByTestId("dirty")).toHaveTextContent("false"));
expect(screen.getByTestId("result")).toHaveTextContent("success");
});
it("maps only approved 422 fields and never renders backend copy", async () => {
const user = userEvent.setup();
const failure = createFailure(
"VALIDATION_REJECTED",
"CREATE_ENTITY",
0,
{
validationIssues: [
{ path: "name", code: "REQUIRED" },
{ path: "serverOnly", code: "raw-secret-message" },
],
},
);
render(
<FormHarness submit={async () => ({ ok: false, error: failure })} />,
);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Valid");
await user.click(screen.getByRole("button", { name: "Submit" }));
expect(await screen.findByRole("alert")).toHaveTextContent("필수 입력값입니다.");
expect(screen.getByRole("alert")).toHaveTextContent(
"서버가 확인하지 못한 입력 항목",
);
expect(document.body).not.toHaveTextContent("raw-secret-message");
});
// 백엔드 1101/02-01 후속. The paired backend answers a field validation
// failure with 400 VALIDATION_FAILED and details [{field, code, message}]
// (its docs/web/http-contract.md §4). It reaches the form through the HTTP
// executor and lands on the same allowed fields a 422 does.
it("maps a paired backend 400 VALIDATION_FAILED onto the form fields", async () => {
const user = userEvent.setup();
const http = formBinding(async () =>
Response.json(
{
success: false,
error: {
code: "VALIDATION_FAILED",
category: "VALIDATION",
message: "요청 값이 올바르지 않습니다.",
retryable: false,
details: [
{ field: "name", code: "NOT_BLANK", message: "raw backend copy" },
{ field: "request", code: "INVALID", message: "raw backend copy" },
],
},
meta: { requestId: "request-1", traceId: "trace-1" },
},
{ status: 400 },
),
);
render(
<FormHarness
submit={async (command) => {
const result = await http.execute(
"FORM_CREATE_ENTITY",
{ name: command.name },
{
intent: Object.freeze({
intentId: "intent-1",
operationId: "FORM_CREATE_ENTITY",
canonicalInputIdentity: "{}",
idempotencyKey: "key-1",
createdAtMonotonicMs: 0,
}),
},
);
if (result.ok) throw new Error("expected a validation failure");
return result;
}}
/>,
);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Valid");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("validation-error"),
);
expect(screen.getByRole("textbox", { name: /Name/ })).toHaveAttribute(
"aria-invalid",
"true",
);
expect(screen.getByRole("textbox", { name: /Note/ })).not.toHaveAttribute(
"aria-invalid",
);
// A class-level error names no form field.
expect(screen.getByRole("alert")).toHaveTextContent(
"서버가 확인하지 못한 입력 항목",
);
expect(document.body).not.toHaveTextContent("raw backend copy");
});
it.each([
[
"AUTH_REQUIRED",
"reauth-required",
"계속하려면 로그인이 필요합니다.",
"로그인",
],
[
"FORBIDDEN",
"forbidden",
"이 작업을 수행할 권한이 없습니다.",
"안전한 화면으로 이동",
],
[
"RATE_LIMITED",
"retry-later",
"요청이 많습니다. 잠시 후 다시 시도해 주세요.",
"다시 시도",
],
] as const)(
"shows %s as its own save state, not an input error",
async (kind, result, copy, action) => {
const user = userEvent.setup();
const onFailureAction = vi.fn();
const submit = vi.fn(async () => ({
ok: false as const,
error: createFailure(kind, "CREATE_ENTITY", 0, {
effect: "NOT_APPLIED",
}),
}));
render(
<FormHarness submit={submit} onFailureAction={onFailureAction} />,
);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Valid");
await user.click(screen.getByRole("button", { name: "Submit" }));
expect(await screen.findByTestId("result")).toHaveTextContent(result);
expect(screen.getByRole("alert")).toHaveTextContent(copy);
expect(document.body).not.toHaveTextContent("입력 내용을 확인해 주세요.");
expect(document.body).not.toHaveTextContent("저장하지 못했습니다.");
expect(
document.body.textContent?.includes("입력한 내용은 사라집니다"),
).toBe(kind === "AUTH_REQUIRED");
expect(screen.getByRole("textbox", { name: /Name/ })).toHaveValue("Valid");
await user.click(screen.getByRole("button", { name: action }));
if (kind === "RATE_LIMITED") {
expect(submit).toHaveBeenCalledTimes(2);
expect(onFailureAction).not.toHaveBeenCalled();
} else {
expect(onFailureAction).toHaveBeenCalledOnce();
}
},
);
// F-10 (08-01). A save that failed for a reason the user cannot fix in the
// input is a status with its own action, never an input error summary.
it.each([
["NOT_FOUND", "요청한 항목을 찾을 수 없습니다.", "안전한 화면으로 이동"],
["UNKNOWN_CLIENT_FAILURE", "요청을 처리할 수 없습니다.", "지원 정보 확인"],
] as const)(
"shows an unavailable %s save as a status, not an input error",
async (kind, copy, action) => {
const user = userEvent.setup();
const onFailureAction = vi.fn();
render(
<FormHarness
submit={async () => ({
ok: false,
error: createFailure(kind, "CREATE_ENTITY", 0, {
effect: "NOT_APPLIED",
}),
})}
onFailureAction={onFailureAction}
/>,
);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Valid");
await user.click(screen.getByRole("button", { name: "Submit" }));
expect(await screen.findByTestId("result")).toHaveTextContent(
"unavailable",
);
expect(screen.getByRole("alert")).toHaveTextContent(copy);
expect(document.body).not.toHaveTextContent("입력 내용을 확인해 주세요.");
await user.click(screen.getByRole("button", { name: action }));
expect(onFailureAction).toHaveBeenCalledOnce();
},
);
// 0929/08-04. A failed or unknown save carries the id a user quotes to
// support, the same as a failed query.
it("shows the save failure's request id as its support reference", async () => {
const user = userEvent.setup();
render(
<FormHarness
submit={async () => ({
ok: false,
error: createFailure("UNKNOWN_CLIENT_FAILURE", "CREATE_ENTITY", 0, {
effect: "NOT_APPLIED",
requestId: "corr-save-400",
}),
})}
/>,
);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Valid");
await user.click(screen.getByRole("button", { name: "Submit" }));
expect(await screen.findByRole("alert")).toHaveTextContent(
"지원 참조: corr-save-400",
);
expect(screen.getByTestId("support")).toHaveTextContent("corr-save-400");
});
it("keeps the request id of a save whose effect is unknown", async () => {
const user = userEvent.setup();
render(
<FormHarness
submit={async () => ({
ok: false,
error: createFailure("SERVER_FAILURE", "CREATE_ENTITY", 0, {
effect: "MAYBE_APPLIED",
requestId: "corr-save-500",
}),
})}
resetOnSuccess={false}
/>,
);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Valid");
await user.click(screen.getByRole("button", { name: "Submit" }));
expect(await screen.findByTestId("result")).toHaveTextContent("effect-unknown");
expect(screen.getByTestId("support")).toHaveTextContent("corr-save-500");
await user.click(screen.getByRole("button", { name: "Confirm applied" }));
expect(screen.getByTestId("support")).toHaveTextContent("");
});
it("keeps conflict input out of URL and storage", async () => {
const user = userEvent.setup();
localStorage.clear();
window.history.replaceState({}, "", "/form-test");
render(
<FormHarness
submit={async () => ({
ok: false,
error: createFailure("CONFLICT", "CREATE_ENTITY", 0),
})}
/>,
);
const secretLike = "token-like-do-not-copy";
await user.type(screen.getByRole("textbox", { name: /Name/ }), secretLike);
await user.click(screen.getByRole("button", { name: "Submit" }));
expect(await screen.findByText(/다른 변경과 충돌했습니다/)).toBeVisible();
expect(screen.getByRole("textbox", { name: /Name/ })).toHaveValue(secretLike);
expect(window.location.href).not.toContain(secretLike);
expect(JSON.stringify(localStorage)).not.toContain(secretLike);
});
it("blocks a second submit while the prior effect remains unknown", async () => {
const user = userEvent.setup();
const submit = vi.fn(async () => ({
ok: false as const,
error: createFailure("SERVER_FAILURE", "CREATE_ENTITY", 0, {
effect: "MAYBE_APPLIED",
}),
}));
render(<FormHarness submit={submit} resetOnSuccess={false} />);
const name = screen.getByRole("textbox", { name: /Name/ });
await user.type(name, "Alpha");
await user.click(screen.getByRole("button", { name: "Submit" }));
expect(await screen.findByTestId("result")).toHaveTextContent(
"effect-unknown",
);
await user.clear(name);
await user.type(name, "Beta");
await user.click(screen.getByRole("button", { name: "Submit" }));
expect(submit).toHaveBeenCalledOnce();
expect(screen.getByTestId("result")).toHaveTextContent("effect-unknown");
});
it("settles the submitted unknown snapshot without accepting later edits", async () => {
const user = userEvent.setup();
const submit = vi.fn(async () => ({
ok: false as const,
error: createFailure("SERVER_FAILURE", "CREATE_ENTITY", 0, {
effect: "MAYBE_APPLIED",
}),
}));
render(<FormHarness submit={submit} resetOnSuccess={false} />);
const name = screen.getByRole("textbox", { name: /Name/ });
await user.type(name, "Alpha");
await user.click(screen.getByRole("button", { name: "Submit" }));
await screen.findByText("effect-unknown");
await user.clear(name);
await user.type(name, "Beta");
await user.click(screen.getByRole("button", { name: "Confirm applied" }));
expect(name).toHaveValue("Beta");
expect(screen.getByTestId("result")).toHaveTextContent("success");
expect(screen.getByTestId("dirty")).toHaveTextContent("true");
await user.clear(name);
await user.type(name, "Alpha");
expect(screen.getByTestId("dirty")).toHaveTextContent("false");
});
it("releases an unknown submission only after explicit not-applied settlement", async () => {
const user = userEvent.setup();
const submit = vi
.fn()
.mockResolvedValueOnce({
ok: false as const,
error: createFailure("SERVER_FAILURE", "CREATE_ENTITY", 0, {
effect: "MAYBE_APPLIED",
}),
})
.mockResolvedValueOnce({ ok: true as const, value: "saved" });
render(<FormHarness submit={submit} resetOnSuccess={false} />);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Alpha");
await user.click(screen.getByRole("button", { name: "Submit" }));
await screen.findByText("effect-unknown");
await user.click(
screen.getByRole("button", { name: "Confirm not applied" }),
);
expect(screen.getByTestId("result")).toHaveTextContent("idle");
await user.click(screen.getByRole("button", { name: "Submit" }));
expect(submit).toHaveBeenCalledTimes(2);
});
});
describe("dirty navigation guard", () => {
it("blocks navigation, restores focus on stay and proceeds explicitly", async () => {
const user = userEvent.setup();
function GuardedPage() {
const navigate = useNavigate();
const [dirty, setDirty] = useState(false);
const guard = useDirtyNavigationGuard(dirty);
return (
<>
<label htmlFor="guard-field">Guard field</label>
<input
id="guard-field"
onChange={() => setDirty(true)}
/>
<Button onClick={() => navigate("/target")}>Leave</Button>
<DirtyNavigationDialog guard={guard} />
</>
);
}
const router = createMemoryRouter(
[
{ path: "/", element: <GuardedPage /> },
{ path: "/target", element: <h1>Target</h1> },
],
{ initialEntries: ["/"] },
);
render(<RouterProvider router={router} />);
await user.type(screen.getByRole("textbox", { name: "Guard field" }), "x");
const leave = screen.getByRole("button", { name: "Leave" });
await user.click(leave);
expect(
screen.getByRole("dialog", { name: "저장하지 않은 변경이 있습니다." }),
).toHaveAttribute("open");
await user.click(screen.getByRole("button", { name: "계속 작성" }));
await waitFor(() => expect(leave).toHaveFocus());
await user.click(leave);
await user.click(screen.getByRole("button", { name: "변경 버리고 이동" }));
expect(await screen.findByRole("heading", { name: "Target" })).toBeVisible();
});
});
describe("submission timing", () => {
it("submits once when a second submit arrives during async validation", async () => {
const user = userEvent.setup();
let releaseValidation: () => void = () => {};
const validationGate = new Promise<void>((resolve) => {
releaseValidation = resolve;
});
const asyncSchema = schema.refine(async () => {
await validationGate;
return true;
});
const submit = vi.fn(async () => ({ ok: true as const, value: "saved" }));
function AsyncForm() {
const form = useAppForm({
schema: asyncSchema,
defaultValues: defaults,
allowedServerFields: ["name", "note"],
mapToCommand: (values) => ({ name: values.name }),
submit,
});
return (
<Form pending={form.pending} onSubmit={(event) => void form.submitForm(event)}>
<FormField {...form.field("name")} label="Name" required />
<Button type="submit">Submit</Button>
<output data-testid="result">{form.result}</output>
<output data-testid="support">{form.supportReference ?? ""}</output>
</Form>
);
}
render(<AsyncForm />);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Ready");
await user.click(screen.getByRole("button", { name: "Submit" }));
await user.click(screen.getByRole("button", { name: "Submit" }));
releaseValidation();
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("success"),
);
expect(submit).toHaveBeenCalledOnce();
});
it("does not ask to discard changes when navigating right after a save", async () => {
const user = userEvent.setup();
function SaveThenLeave() {
const navigate = useNavigate();
const form = useAppForm({
schema,
defaultValues: defaults,
allowedServerFields: ["name", "note"],
mapToCommand: (values) => ({ name: values.name }),
submit: async () => ({ ok: true as const, value: "saved" }),
});
const guard = useDirtyNavigationGuard(form.dirty);
return (
<Form
onSubmit={(event) => {
void form.submitForm(event).then((outcome) => {
if (outcome?.ok) void navigate("/done");
});
}}
pending={form.pending}
>
<FormField {...form.field("name")} label="Name" required />
<Button type="submit">Save</Button>
<DirtyNavigationDialog guard={guard} />
</Form>
);
}
const router = createMemoryRouter(
[
{ path: "/", element: <SaveThenLeave /> },
{ path: "/done", element: <h1>Done</h1> },
],
{ initialEntries: ["/"] },
);
render(<RouterProvider router={router} />);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Ready");
await user.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByRole("heading", { name: "Done" })).toBeVisible();
expect(
screen.queryByRole("dialog", { name: "저장하지 않은 변경이 있습니다." }),
).not.toBeInTheDocument();
});
});
/**
* A server validation refusal through the HTTP executor and the mutation
* coordinator, with the reference form page's gate: the save button is off
* while the coordinator holds an unknown effect.
*/
describe("correcting a field after a server validation refusal", () => {
let token = 0;
const scope = {
...scopeSnapshot(),
identities: createRuntimeIdentityRegistry({
tokenFactory: () => `form-identity-token-${String(++token).padStart(4, "0")}`,
}),
};
function CoordinatedForm(props: Readonly<{ fetcher: typeof fetch }>) {
const [http] = useState(() => formBinding(props.fetcher));
const mutation = useApplicationMutation<
Readonly<{ name: string; note?: string }>,
unknown
>({
definitionId: "form-create-v1",
definitionVersion: 1,
operationId: "FORM_CREATE_ENTITY",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "REJECT_WHILE_ACTIVE",
scope,
invalidate: [],
execute: (command, { intent }) =>
http.execute("FORM_CREATE_ENTITY", { name: command.name }, { intent }),
});
const form = useAppForm({
schema,
defaultValues: defaults,
allowedServerFields: ["name", "note"],
mapToCommand: (values) => ({ name: values.name }),
submit: mutation.submit,
});
const blocked =
mutation.state.indicator === "mutation-effect-unknown" ||
mutation.state.indicator === "mutation-pending";
return (
<Form pending={form.pending} onSubmit={(event) => void form.submitForm(event)}>
<FormField {...form.field("name")} label="Name" required />
<Button type="submit" disabled={form.pending || blocked}>
Submit
</Button>
<output data-testid="result">{form.result}</output>
</Form>
);
}
const meta = { requestId: "request-1", traceId: "trace-1" };
function answerFirst(status: number, error: unknown) {
return vi
.fn<typeof fetch>()
.mockResolvedValueOnce(
Response.json({ success: false, error, meta }, { status }),
)
.mockImplementation(async () =>
Response.json({
success: true,
data: { id: "entity-1", name: "Fixed" },
meta,
}),
);
}
// 백엔드 1101/02-01 후속. The paired backend's 400 VALIDATION_FAILED with
// the field list (its docs/web/http-contract.md §4).
it("saves the corrected value after a 400 field error", async () => {
const user = userEvent.setup();
const fetcher = answerFirst(400, {
code: "VALIDATION_FAILED",
details: [{ field: "name", code: "NOT_BLANK", message: "필수 값이 없습니다." }],
});
render(<CoordinatedForm fetcher={fetcher} />, {
wrapper: wrapper(queryClient()),
});
const name = screen.getByRole("textbox", { name: /Name/ });
await user.type(name, "Rejected");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() => expect(name).toHaveAttribute("aria-invalid", "true"));
await user.clear(name);
await user.type(name, "Fixed");
expect(screen.getByRole("button", { name: "Submit" })).toBeEnabled();
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("success"),
);
expect(fetcher).toHaveBeenCalledTimes(2);
});
// 1101/14.4. A body the backend could not read is refused while binding,
// before any write (frontend contract 6.1), so the save is not held.
it("saves again after a 400 VALIDATION_FAILED whose body did not parse", async () => {
const user = userEvent.setup();
const fetcher = answerFirst(400, {
code: "VALIDATION_FAILED",
details: { cause: "JsonParseException" },
});
render(<CoordinatedForm fetcher={fetcher} />, {
wrapper: wrapper(queryClient()),
});
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Fixed");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1));
await waitFor(() =>
expect(screen.getByRole("button", { name: "Submit" })).toBeEnabled(),
);
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("success"),
);
expect(fetcher).toHaveBeenCalledTimes(2);
});
// 1101/14.4. Outside IDEMPOTENT_REQUEST_MISMATCH a 422 may come after a
// write (fileserver INTEGRITY_MISMATCH), so the coordinator holds it as an
// unknown result even though the form shows the field.
it("keeps the save off after a 422 the backend may have applied", async () => {
const user = userEvent.setup();
const fetcher = answerFirst(422, {
code: "INVALID_INPUT",
details: { issues: [{ path: "name", code: "REQUIRED" }] },
});
render(<CoordinatedForm fetcher={fetcher} />, {
wrapper: wrapper(queryClient()),
});
const name = screen.getByRole("textbox", { name: /Name/ });
await user.type(name, "Rejected");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() => expect(name).toHaveAttribute("aria-invalid", "true"));
expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled();
expect(fetcher).toHaveBeenCalledTimes(1);
});
});