Files
clean-architecture-frontend…/tests/component/form-foundation.test.tsx
T
DongHyeonka fb6cbdc37f test(create-feature): 생성 페이지 시험이 저장 규칙을 플랫폼 폼에서 찾는다
FE-GATE-020 drill에서 create-feature.test.ts 셋이 실패했다. 생성 작성
페이지의 옛 사본(otherSaveRunning 계산, mounted ref)을 문자열로 단언한다.
이 PR에서 그 규칙은 플랫폼 폼(useAppForm `mutation`·`onSaved`,
FormSaveFeedback)으로 옮겼고 form-foundation 시험이 걷는다(1105/08-04,
1106/08-02). 생성 페이지 시험은 페이지가 폼 상태로 버튼을 끄고, 저장 뒤
이동을 onSaved·onConfirmed에 두며, 마운트 표시를 두지 않는지 본다.

다시 마운트한 폼의 막기 시험은 막기를 지운 변이에서도 통과했다. 빈 이름이라
입력 검증이 멈췄고, 이름을 넣어도 코디네이터가 따로 새 요청을 막아 네트워크
호출 수가 같았다. 유효한 이름을 넣고, 폼이 mutation에 저장을 넘기는지를 직접
센다.

검증: 막기 변이에서 그 시험이 실패하고, create-feature·form-foundation과
FE-GATE-005·020이 통과하는지 desktop에서 본다(PR 본문).

Refs: 1112/01-01, 1105/08-04, 1106/08-02
2026-11-13 03:45:37 +09:00

1718 lines
64 KiB
TypeScript

// @vitest-environment jsdom
import { fireEvent, 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 { commandMutationIdentity } from "../../src/contracts/server-state.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,
FormSaveFeedback,
useAppForm,
useDirtyNavigationGuard,
validationMessage,
} from "../../src/presentation/forms/index.ts";
import {
formatMessage,
type ParameterlessMessageKey,
} from "../../src/presentation/i18n/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),
}),
});
/**
* 1103/03-01. The same create, declaring the paired backend scaffold's
* `<FEATURE>_INVALID` (and a 409 business code checked before the write) as
* refused before the write.
*/
const FORM_DECLARING_OPERATIONS = Object.freeze({
FORM_CREATE_ENTITY: defineFeatureHttpOperation({
contract: Object.freeze({
...FORM_CREATE_CONTRACT,
contract: Object.freeze({
...FORM_CREATE_CONTRACT.contract,
commandEffect: Object.freeze({
...FORM_CREATE_CONTRACT.contract.commandEffect,
refusedBeforeWrite: Object.freeze(["WORKLOG_INVALID", "POSTER_ALREADY_EXISTS"]),
}),
}),
}),
routeId: "FORM_ROUTE",
mapSuccess: (value) => mappingSuccess(value),
}),
});
function formBinding(
fetcher: typeof fetch,
operations:
| typeof FORM_OPERATIONS
| typeof FORM_DECLARING_OPERATIONS = FORM_OPERATIONS,
) {
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 }),
}),
}),
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;
/** Resends the save an earlier mount left unknown (`resendUnknown`). */
resend?(): Promise<
| Readonly<{ ok: true; value: string }>
| Readonly<{ ok: false; error: ReturnType<typeof createFailure> }>
>;
}>) {
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,
});
const resend = props.resend;
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>
{resend ? (
<Button onClick={() => void form.resendUnknown(resend)}>Resend</Button>
) : null}
<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",
);
// NOT_BLANK has its own copy, not the "check the value" default.
expect(screen.getByRole("alert")).toHaveTextContent("필수 입력값입니다.");
// A class-level error names no form field.
expect(screen.getByRole("alert")).toHaveTextContent(
"서버가 확인하지 못한 입력 항목",
);
expect(document.body).not.toHaveTextContent("raw backend copy");
});
// 1103/08-05. The same key went out with another body. The user has
// nothing to correct, so the form shows a status with a support reference.
it("shows a paired backend 422 IDEMPOTENT_REQUEST_MISMATCH as a status, not an input error", async () => {
const user = userEvent.setup();
const http = formBinding(async () =>
Response.json(
{
success: false,
error: {
code: "IDEMPOTENT_REQUEST_MISMATCH",
category: "VALIDATION",
message: "요청 값이 올바르지 않습니다.",
retryable: false,
},
meta: { requestId: "request-1", traceId: "trace-1" },
},
{ status: 422, headers: { "x-correlation-id": "corr-422" } },
),
);
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 mismatch refusal");
return result;
}}
/>,
);
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(document.body).not.toHaveTextContent("입력값을 다시 확인해 주세요.");
expect(screen.getByRole("textbox", { name: /Name/ })).not.toHaveAttribute(
"aria-invalid",
);
expect(screen.getByRole("alert")).toHaveTextContent("지원 참조: corr-422");
expect(screen.getByRole("button", { name: "Submit" })).toBeEnabled();
});
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);
});
});
// 1106/08-01, 1106/03-01 (diff review FR-03), 1112/10-01. A page left while
// its save was unknown comes back with a new form: the coordinator still
// holds the unknown save, the form no longer knows the values it sent. The
// values on screen were typed after the save and never sent, so no way out
// of the unknown result may take them as the saved values: they and the
// dirty state stay as they are, and the leave guard still protects them.
describe("a form mounted again while its save is unknown", () => {
const leftUnknown = () =>
Promise.resolve({
ok: false as const,
error: createFailure("RATE_LIMITED", "CREATE_ENTITY", 0, {
effect: "NOT_APPLIED",
httpStatus: 429,
code: "RATE_LIMIT_EXCEEDED",
}),
});
it("keeps the values on screen when the earlier save is confirmed applied", async () => {
const user = userEvent.setup();
const submit = vi.fn();
render(<FormHarness submit={submit} />);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Beta");
await user.click(screen.getByRole("button", { name: "Confirm applied" }));
expect(screen.getByTestId("result")).toHaveTextContent("success");
expect(screen.getByRole("textbox", { name: /Name/ })).toHaveValue("Beta");
expect(screen.getByTestId("dirty")).toHaveTextContent("true");
expect(submit).not.toHaveBeenCalled();
});
it("keeps the values on screen when the resend succeeds", async () => {
const user = userEvent.setup();
const resend = vi.fn(async () => ({ ok: true as const, value: "saved" }));
render(<FormHarness submit={vi.fn()} resend={resend} />);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Beta");
await user.click(screen.getByRole("button", { name: "Resend" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("success"),
);
expect(resend).toHaveBeenCalledTimes(1);
expect(screen.getByRole("textbox", { name: /Name/ })).toHaveValue("Beta");
expect(screen.getByTestId("dirty")).toHaveTextContent("true");
});
it("keeps the values on screen when a resend left unknown is then confirmed applied", async () => {
const user = userEvent.setup();
render(<FormHarness submit={vi.fn()} resend={leftUnknown} />);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Beta");
await user.click(screen.getByRole("button", { name: "Resend" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("effect-unknown"),
);
await user.click(screen.getByRole("button", { name: "Confirm applied" }));
expect(screen.getByTestId("result")).toHaveTextContent("success");
expect(screen.getByRole("textbox", { name: /Name/ })).toHaveValue("Beta");
expect(screen.getByTestId("dirty")).toHaveTextContent("true");
});
});
// 1101/14.4. Every code the paired backend can put in a field error's
// details[].code: clean-architecture-backend-template 5786126c,
// ClientSafeValidationDetails.java RULES (18-42) and its INVALID fallback.
// http-contract.md §4 names the shape, not the list. A code missing from the
// form copy table shows the "check the value" default instead.
const BACKEND_FIELD_CODES = [
"NOT_NULL",
"NOT_BLANK",
"NOT_EMPTY",
"SIZE",
"MIN",
"MAX",
"POSITIVE",
"POSITIVE_OR_ZERO",
"NEGATIVE",
"NEGATIVE_OR_ZERO",
"PATTERN",
"EMAIL",
"PAST",
"PAST_OR_PRESENT",
"FUTURE",
"FUTURE_OR_PRESENT",
"ASSERT_TRUE",
"ASSERT_FALSE",
"TYPE_MISMATCH",
"INVALID",
] as const;
describe("paired backend field codes", () => {
it.each(["ko-KR", "en-US"] as const)(
"gives every backend field code its own %s copy",
(locale) => {
const message = (key: ParameterlessMessageKey) =>
formatMessage(locale, key);
const fallback = message("form.validation.unknown");
expect(
BACKEND_FIELD_CODES.filter(
(code) => validationMessage(code, message) === fallback,
),
).toEqual([]);
},
);
it.each(["SOME_FUTURE_CODE", "constructor", "toString", "__proto__", "hasOwnProperty"])(
"keeps the default copy for a code it does not know (%s)",
(code) => {
// 1103/08-03. Names inherited from Object.prototype are unknown codes too.
expect(validationMessage(code)).toBe(
formatMessage("ko-KR", "form.validation.unknown"),
);
},
);
});
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;
operations?: typeof FORM_DECLARING_OPERATIONS;
refusalMessages?: Readonly<
Record<
string,
Readonly<{ message: ParameterlessMessageKey; field?: "name" | "note" }>
>
>;
}>,
) {
const [http] = useState(() => formBinding(props.fetcher, props.operations));
const mutation = useApplicationMutation<
Readonly<{ name: string; note?: string }>,
unknown
>({
definitionId: "form-create-v1",
definitionVersion: 1,
operationId: commandMutationIdentity(FORM_CREATE_CONTRACT).operationId,
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,
refusalMessages: props.refusalMessages,
});
const blocked =
mutation.state.indicator === "mutation-effect-unknown" ||
mutation.state.indicator === "mutation-pending";
return (
<Form pending={form.pending} onSubmit={(event) => void form.submitForm(event)}>
{props.refusalMessages ? (
<ErrorSummary
fieldErrors={form.fieldErrors}
formErrors={form.formErrors}
fieldLabels={{ name: "Name", note: "Note" }}
fieldId={form.fieldId}
onFocusField={form.focusField}
/>
) : null}
<FormField {...form.field("name")} label="Name" required />
<Button type="submit" disabled={form.pending || blocked}>
Submit
</Button>
<Button onClick={() => void form.resendUnknown(mutation.resendUnknownEffect)}>
Resend
</Button>
<output data-testid="result">{form.result}</output>
<output data-testid="indicator">{mutation.state.indicator ?? "none"}</output>
<output data-testid="form-errors">{form.formErrors.join(" ")}</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);
});
function sentKeys(fetcher: ReturnType<typeof answerFirst>) {
return fetcher.mock.calls.map(
([, init]) => (init?.headers as Readonly<Record<string, string>>)["Idempotency-Key"],
);
}
// 1103/03-01 (= 08-01). The paired backend scaffold's create refuses a bad
// name with 400 <FEATURE>_INVALID before its transaction. Declared on the
// operation, the refusal is not an unknown result: the user corrects the
// value and saves again, and the second request is a new one.
it("saves the corrected value after a declared pre-write refusal, with a new key", async () => {
const user = userEvent.setup();
const fetcher = answerFirst(400, { code: "WORKLOG_INVALID" });
render(
<CoordinatedForm fetcher={fetcher} operations={FORM_DECLARING_OPERATIONS} />,
{ 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(screen.getByTestId("result")).toHaveTextContent("unavailable"),
);
expect(screen.getByRole("button", { name: "Submit" })).toBeEnabled();
await user.clear(name);
await user.type(name, "Fixed");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("success"),
);
expect(fetcher).toHaveBeenCalledTimes(2);
expect(sentKeys(fetcher)).toEqual(["key-1", "key-2"]);
});
// 1103/03-01 (remaining part). The declared refusal in the feature's own
// words, on the field it names, instead of the platform's unavailable
// status and its support action. A feature passes a key of its catalog.
it("shows the feature's words for a declared refusal on its field and saves again", async () => {
const user = userEvent.setup();
const fetcher = answerFirst(400, { code: "WORKLOG_INVALID" });
render(
<CoordinatedForm
fetcher={fetcher}
operations={FORM_DECLARING_OPERATIONS}
refusalMessages={{
WORKLOG_INVALID: { field: "name", message: "form.validation.invalidFormat" },
}}
/>,
{ 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(screen.getByTestId("result")).toHaveTextContent("validation-error"),
);
expect(name).toHaveAttribute("aria-invalid", "true");
expect(name).toHaveFocus();
expect(screen.getByRole("alert")).toHaveTextContent(
`Name: ${formatMessage("ko-KR", "form.validation.invalidFormat")}`,
);
expect(screen.getByRole("button", { name: "Submit" })).toBeEnabled();
await user.clear(name);
await user.type(name, "Fixed");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("success"),
);
expect(sentKeys(fetcher)).toEqual(["key-1", "key-2"]);
});
it("shows a declared refusal without a field in the error summary", async () => {
const user = userEvent.setup();
const fetcher = answerFirst(409, { code: "POSTER_ALREADY_EXISTS" });
render(
<CoordinatedForm
fetcher={fetcher}
operations={FORM_DECLARING_OPERATIONS}
refusalMessages={{
POSTER_ALREADY_EXISTS: { message: "form.validation.invalidValue" },
}}
/>,
{ wrapper: wrapper(queryClient()) },
);
const name = screen.getByRole("textbox", { name: /Name/ });
await user.type(name, "Taken");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("validation-error"),
);
expect(screen.getByRole("alert")).toHaveTextContent(
formatMessage("ko-KR", "form.validation.invalidValue"),
);
expect(screen.getByRole("alert")).not.toHaveTextContent(
formatMessage("ko-KR", "form.conflict"),
);
expect(name).not.toHaveAttribute("aria-invalid");
expect(screen.getByRole("button", { name: "Submit" })).toBeEnabled();
});
// An unknown result stays unknown: the words are for a refusal that did
// not apply, never for one that may have.
it("keeps an undeclared refusal unknown even when the form has words for its code", async () => {
const user = userEvent.setup();
const fetcher = answerFirst(400, { code: "WORKLOG_INVALID" });
render(
<CoordinatedForm
fetcher={fetcher}
refusalMessages={{
WORKLOG_INVALID: { field: "name", message: "form.validation.invalidFormat" },
}}
/>,
{ wrapper: wrapper(queryClient()) },
);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Rejected");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("effect-unknown"),
);
expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled();
});
// 1103/03-01. A code the operation did not declare may have been raised
// after a write, so the coordinator keeps holding it.
it("keeps the save off after a business refusal the operation did not declare", async () => {
const user = userEvent.setup();
const fetcher = answerFirst(400, { code: "WORKLOG_INVALID" });
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(screen.getByTestId("result")).toHaveTextContent("effect-unknown"),
);
await user.clear(name);
await user.type(name, "Fixed");
expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled();
expect(fetcher).toHaveBeenCalledTimes(1);
});
// 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. 1101/03-04. The form shows that result, not the field it
// names: correcting the field would send a second save.
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(screen.getByTestId("result")).toHaveTextContent("effect-unknown"),
);
expect(name).not.toHaveAttribute("aria-invalid");
expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled();
expect(fetcher).toHaveBeenCalledTimes(1);
});
// 1106/03-01. The answer is lost, and the same-key resend meets the edge
// rate limiter's 503 RATE_LIMIT_UNAVAILABLE, refused before the write. The
// first request may still have applied: the result stays unknown, a save
// sends nothing new, and the next resend carries the same key (review
// experiment 03-R1 X5: keys key-1, key-1, key-2).
it("keeps a lost create unknown when its resend is refused before the write", async () => {
const user = userEvent.setup();
const fetcher = vi
.fn<typeof fetch>()
.mockRejectedValueOnce(new TypeError("Failed to fetch"))
.mockResolvedValueOnce(
Response.json(
{
success: false,
error: {
code: "RATE_LIMIT_UNAVAILABLE",
category: "TRANSIENT_DEPENDENCY",
retryable: true,
},
meta,
},
{ status: 503 },
),
)
.mockImplementation(async () =>
Response.json({
success: true,
data: { id: "entity-1", name: "Saved" },
meta,
}),
);
const { container } = render(<CoordinatedForm fetcher={fetcher} />, {
wrapper: wrapper(queryClient()),
});
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Saved");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("effect-unknown"),
);
await user.click(screen.getByRole("button", { name: "Resend" }));
await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2));
await waitFor(() =>
expect(screen.getByTestId("form-errors")).toHaveTextContent(
formatMessage("ko-KR", "form.resendLater"),
),
);
expect(screen.getByTestId("result")).toHaveTextContent("effect-unknown");
expect(screen.getByTestId("indicator")).toHaveTextContent(
"mutation-effect-unknown",
);
expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled();
// A save that reaches the form anyway (Enter in the field) sends nothing.
const form = container.querySelector("form");
if (!form) throw new Error("expected the form");
fireEvent.submit(form);
expect(fetcher).toHaveBeenCalledTimes(2);
await user.click(screen.getByRole("button", { name: "Resend" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("success"),
);
expect(sentKeys(fetcher)).toEqual(["key-1", "key-1", "key-1"]);
});
// 1106/03-01 (D10 supplement). The same-key resend meets the backend's 400
// VALIDATION_FAILED, which every attempt of that request gets: the first
// was refused too. The form is not held: it shows the field error, and the
// corrected value goes out as a new request. Before, the save stayed off
// and the only ways out were a false "confirm applied" or a reload.
it("takes a corrected save after a resend refused with 400 VALIDATION_FAILED", async () => {
const user = userEvent.setup();
const fetcher = vi
.fn<typeof fetch>()
.mockRejectedValueOnce(new TypeError("Failed to fetch"))
.mockResolvedValueOnce(
Response.json(
{
success: false,
error: {
code: "VALIDATION_FAILED",
details: [{ field: "name", code: "NOT_BLANK", message: "필수 값이 없습니다." }],
},
meta,
},
{ status: 400 },
),
)
.mockImplementation(async () =>
Response.json({
success: true,
data: { id: "entity-1", name: "Fixed" },
meta,
}),
);
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(screen.getByTestId("result")).toHaveTextContent("effect-unknown"),
);
await user.click(screen.getByRole("button", { name: "Resend" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("validation-error"),
);
expect(name).toHaveAttribute("aria-invalid", "true");
expect(screen.getByTestId("indicator")).toHaveTextContent("none");
expect(screen.getByRole("button", { name: "Submit" })).toBeEnabled();
await user.clear(name);
await user.type(name, "Fixed");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("success"),
);
expect(sentKeys(fetcher)).toEqual(["key-1", "key-1", "key-2"]);
});
});
// 1112/01-01. The page used to hold the rules of a save through a mutation:
// it refused a new save while the coordinator held one unknown or running,
// and it wired the unknown-result surface's confirm and resend to the form.
// A generated page kept its own copy, so a platform fix never reached it.
// Now the form takes the mutation and FormSaveFeedback draws the feedback.
describe("a form bound to its mutation", () => {
let token = 0;
const scope = {
...scopeSnapshot(),
identities: createRuntimeIdentityRegistry({
tokenFactory: () => `bound-identity-token-${String(++token).padStart(4, "0")}`,
}),
};
const meta = { requestId: "request-1", traceId: "trace-1" };
function BoundForm(
props: Readonly<{
fetcher: typeof fetch;
operations?: typeof FORM_DECLARING_OPERATIONS;
onSaved?: (value: unknown) => void;
onConfirmed?: () => void;
/** Counts the saves the form hands to the mutation. */
onSubmit?: () => void;
}>,
) {
const [http] = useState(() => formBinding(props.fetcher, props.operations));
const mutation = useApplicationMutation<Readonly<{ name: string; note?: string }>, unknown>({
definitionId: "form-bound-create-v1",
definitionVersion: 1,
operationId: commandMutationIdentity(FORM_CREATE_CONTRACT).operationId,
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: (command) => {
props.onSubmit?.();
return mutation.submit(command);
},
mutation,
...(props.onSaved === undefined ? {} : { onSaved: props.onSaved }),
});
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}
/>
<FormField {...form.field("name")} label="Name" required />
<Button type="submit" pending={form.pending} disabled={form.saveBlocked}>
Submit
</Button>
<div id={form.feedbackId} tabIndex={-1}>
<FormSaveFeedback
form={form}
{...(props.onConfirmed === undefined ? {} : { onConfirmed: props.onConfirmed })}
/>
</div>
<output data-testid="result">{form.result}</output>
<output data-testid="indicator">{mutation.state.indicator ?? "none"}</output>
<output data-testid="pending">{String(form.pending)}</output>
<output data-testid="dirty">{String(form.dirty)}</output>
</Form>
);
}
function lostThen(...answers: Response[]) {
const fetcher = vi.fn<typeof fetch>().mockRejectedValueOnce(new TypeError("Failed to fetch"));
for (const answer of answers) fetcher.mockResolvedValueOnce(answer);
return fetcher.mockImplementation(async () =>
Response.json({ success: true, data: { id: "entity-1", name: "Saved" }, meta }),
);
}
async function loseFirstSave(
fetcher: typeof fetch,
props: Omit<Parameters<typeof BoundForm>[0], "fetcher"> = {},
) {
const user = userEvent.setup();
const client = queryClient();
const view = render(<BoundForm fetcher={fetcher} {...props} />, { wrapper: wrapper(client) });
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Saved");
await user.click(screen.getByRole("button", { name: "Submit" }));
await screen.findByText(formatMessage("ko-KR", "async.mutationEffectUnknown"));
return { user, view, client };
}
/** The user leaves the page and comes back: a new form, the same mutation. */
function mountAgain(
view: ReturnType<typeof render>,
client: ReturnType<typeof queryClient>,
props: Parameters<typeof BoundForm>[0],
) {
view.unmount();
return render(<BoundForm {...props} />, { wrapper: wrapper(client) });
}
/** A save the server answers only when the test says so. */
function heldSave() {
let answer: ((response: Response) => void) | undefined;
const fetcher = vi.fn<typeof fetch>(
() =>
new Promise<Response>((resolve) => {
answer = resolve;
}),
);
return {
fetcher,
answer: async () => {
await waitFor(() => expect(answer).toBeDefined());
answer?.(Response.json({ success: true, data: { id: "entity-1", name: "Saved" }, meta }));
},
};
}
// fe-testing (round9 confirm review). A form mounted again holds no
// submission of its own: only the coordinator's unknown result stops it.
it("refuses a new save in a form mounted again while the coordinator holds one unknown", async () => {
const fetcher = lostThen();
const { view, client } = await loseFirstSave(fetcher);
const submits = vi.fn();
const again = mountAgain(view, client, { fetcher, onSubmit: submits });
await screen.findByText(formatMessage("ko-KR", "async.mutationEffectUnknown"));
const form = again.container.querySelector("form");
if (!form) throw new Error("expected the form");
// A valid value of its own, so only the block stops the save.
fireEvent.change(screen.getByRole("textbox", { name: /Name/ }), {
target: { value: "Typed after coming back" },
});
fireEvent.submit(form);
// The form's own rule: it does not hand the save to the mutation at all.
await new Promise((resolve) => setTimeout(resolve, 0));
expect(submits).not.toHaveBeenCalled();
expect(fetcher).toHaveBeenCalledTimes(1);
expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled();
});
// 1105/08-04, moved here from the generated create page test (1112/01-01).
// The user comes back while the save they started still runs: the form
// shows it and sends nothing new.
it("shows a save it did not start and refuses a new one", async () => {
const user = userEvent.setup();
const held = heldSave();
const client = queryClient();
const view = render(<BoundForm fetcher={held.fetcher} />, { wrapper: wrapper(client) });
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Saved");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() => expect(held.fetcher).toHaveBeenCalledTimes(1));
const again = mountAgain(view, client, { fetcher: held.fetcher });
const form = again.container.querySelector("form");
if (!form) throw new Error("expected the form");
fireEvent.submit(form);
expect(await screen.findByText(formatMessage("ko-KR", "async.mutationPending"))).toBeVisible();
expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled();
expect(held.fetcher).toHaveBeenCalledTimes(1);
await held.answer();
});
// 1106/08-02, moved here from the generated create page test. A save that
// ends after the user left does not take them to what it saved.
it.each([
["while the form is there", false, 1],
["once the user left the form", true, 0],
] as const)("opens what was saved only %s", async (_label, leave, opened) => {
const user = userEvent.setup();
const held = heldSave();
const onSaved = vi.fn();
const view = render(<BoundForm fetcher={held.fetcher} onSaved={onSaved} />, {
wrapper: wrapper(queryClient()),
});
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Saved");
await user.click(screen.getByRole("button", { name: "Submit" }));
if (leave) view.unmount();
await held.answer();
await waitFor(() => expect(held.fetcher).toHaveBeenCalledTimes(1));
if (opened) await waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1));
await new Promise((resolve) => setTimeout(resolve, 0));
expect(onSaved).toHaveBeenCalledTimes(opened);
});
// 1105/08-02, moved here from the generated create page test. Confirming
// the unknown result hands over to the page (which opens the list).
it("hands over to the page once the user confirms the save applied", async () => {
const onConfirmed = vi.fn();
const { user } = await loseFirstSave(lostThen(), { onConfirmed });
await user.click(
screen.getByRole("button", { name: formatMessage("ko-KR", "action.confirmMutationApplied") }),
);
await waitFor(() => expect(onConfirmed).toHaveBeenCalledTimes(1));
expect(screen.getByTestId("indicator")).toHaveTextContent("none");
});
// 1112/01-02 영향 (round9 confirm review). Back on the page, the user typed
// a value the first save never had; the resend saves the first one. The
// page opens what was saved with the leave guard on: the typed value is
// still there and unsaved.
it("opens what a resend saved with the values it never sent still guarded", async () => {
const fetcher = lostThen();
const seen: string[] = [];
const onSaved = vi.fn(() => {
seen.push(
`pending=${screen.getByTestId("pending").textContent} dirty=${screen.getByTestId("dirty").textContent}`,
);
});
const { user, view, client } = await loseFirstSave(fetcher);
mountAgain(view, client, { fetcher, onSaved });
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Never sent");
await user.click(
await screen.findByRole("button", { name: formatMessage("ko-KR", "action.resendMutation") }),
);
await waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1));
expect(seen).toEqual(["pending=false dirty=true"]);
expect(screen.getByRole("textbox", { name: /Name/ })).toHaveValue("Never sent");
});
// D-2 (round9 confirm review). The resend meets a sign-in: signing in
// again comes first, before the unknown result that is still held.
it("asks to sign in again before it shows the unknown result", async () => {
const fetcher = lostThen(
Response.json(
{ success: false, error: { code: "UNAUTHENTICATED", category: "AUTH", retryable: false }, meta },
{ status: 401 },
),
);
const { user } = await loseFirstSave(fetcher);
await user.click(
screen.getByRole("button", { name: formatMessage("ko-KR", "action.resendMutation") }),
);
expect(await screen.findByText("계속하려면 로그인이 필요합니다.")).toBeVisible();
expect(
screen.queryByRole("button", { name: formatMessage("ko-KR", "action.resendMutation") }),
).not.toBeInTheDocument();
});
// 1112/04-02, the declared 409. Not an input error: the feedback says it,
// and the "check what you entered" summary does not appear.
it("says a declared conflict in the feedback, not as an input error", async () => {
const user = userEvent.setup();
const fetcher = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(
Response.json(
{ success: false, error: { code: "POSTER_ALREADY_EXISTS", category: "CONFLICT", retryable: false }, meta },
{ status: 409 },
),
);
render(<BoundForm fetcher={fetcher} operations={FORM_DECLARING_OPERATIONS} />, {
wrapper: wrapper(queryClient()),
});
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Taken");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() => expect(screen.getByTestId("result")).toHaveTextContent("conflict"));
expect(screen.getByText(formatMessage("ko-KR", "form.conflict"))).toBeVisible();
expect(
screen.queryByRole("heading", { name: formatMessage("ko-KR", "form.errorSummary") }),
).not.toBeInTheDocument();
});
it("refuses a new save while the coordinator holds one unknown", async () => {
const fetcher = lostThen();
const { view } = await loseFirstSave(fetcher);
const form = view.container.querySelector("form");
if (!form) throw new Error("expected the form");
fireEvent.submit(form);
expect(fetcher).toHaveBeenCalledTimes(1);
expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled();
});
it("confirms the save applied through the form, which settles both", async () => {
const { user } = await loseFirstSave(lostThen());
await user.click(
screen.getByRole("button", { name: formatMessage("ko-KR", "action.confirmMutationApplied") }),
);
await waitFor(() => expect(screen.getByTestId("result")).toHaveTextContent("success"));
expect(screen.getByTestId("indicator")).toHaveTextContent("none");
});
// UX-02 (1112/04-02). The same-key resend was refused before the write: the
// save is still unknown, and the words say so where the unknown result is,
// not under the "check what you entered" summary.
it("says a resend refused before the write in the feedback, not as an input error", async () => {
const fetcher = lostThen(
Response.json(
{
success: false,
error: { code: "RATE_LIMIT_UNAVAILABLE", category: "TRANSIENT_DEPENDENCY", retryable: true },
meta,
},
{ status: 503 },
),
);
const { user } = await loseFirstSave(fetcher);
await user.click(
screen.getByRole("button", { name: formatMessage("ko-KR", "action.resendMutation") }),
);
await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2));
// The harness's <output> elements are statuses too: find the words, then
// the unknown result's status around them.
const notice = await screen.findByText(formatMessage("ko-KR", "form.resendLater"));
expect(notice.closest('[role="status"]')).toHaveTextContent(
formatMessage("ko-KR", "async.mutationEffectUnknown"),
);
expect(
screen.queryByRole("heading", { name: formatMessage("ko-KR", "form.errorSummary") }),
).not.toBeInTheDocument();
expect(screen.getByTestId("result")).toHaveTextContent("effect-unknown");
});
});
// 1101/03-04. A failure that is both a field refusal and possibly applied
// (a feature's mapProblem says VALIDATION_REJECTED, the classifier
// MAYBE_APPLIED) shows the unknown result only: correcting the field would
// send a second save of something that may already be saved.
describe("a possibly applied failure that names a field", () => {
it("shows the unknown result, not a field error", async () => {
const user = userEvent.setup();
const submit = vi.fn(async () => ({
ok: false as const,
error: createFailure("VALIDATION_REJECTED", "CREATE_ENTITY", 0, {
effect: "MAYBE_APPLIED",
validationIssues: [{ path: "name", code: "SIZE" }],
}),
}));
render(<FormHarness submit={submit} />);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Alpha");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() => expect(screen.getByTestId("result")).toHaveTextContent("effect-unknown"));
expect(screen.getByRole("textbox", { name: /Name/ })).not.toHaveAccessibleDescription(/./u);
});
});