Files
DongHyeonka b41990cdd5 fix(query): 재전송 거절의 결과 불명 해제를 짝 백엔드 표 code로만 정한다
문제: 80e7f1d의 isRefusedOnEveryAttempt는 kind가 VALIDATION_REJECTED면 code를
보지 않고 참을 돌려준다. 그 kind는 기능의 mapProblem이 정한다. 생성기는
선언한 <FEATURE>_INVALID를 VALIDATION_REJECTED로 옮기고
(scripts/create-feature-write-slice.ts mapProblem), 참조 기능 gateway는 code와
상관없이 모든 422를 그렇게 옮긴다(reference-http-gateway.ts). 그래서 기능이
선언한 code나 422 IDEMPOTENT_REQUEST_MISMATCH로 끝난 같은 키 재전송이 결과
불명을 푼다. 함수 주석, CHANGELOG, 런북 6.3-4는 이것들이 결과 불명으로
남는다고 적는다. 기존 테스트는 mapProblem 없이 실패를 만들어 이 길을 타지
않았다(최종 리뷰 FR-01).

고른 방법(메인 세션 결정 "D10 보완 2"): 재전송 거절은 짝 백엔드 표의 code일
때만 결과 불명을 푼다. 지금은 400 VALIDATION_FAILED와 400
IDEMPOTENCY_KEY_INVALID다(REFUSALS_OF_EVERY_ATTEMPT, code와 status 함께). kind
줄을 지우고 kind로 입력 검증을 말하던 주석과 런북 6.3-4를 고쳤다. 기능 code는
상태 규칙일 수 있어 mapProblem이 정한 kind를 믿지 않는다. 400
VALIDATION_FAILED는 필드 목록이 있든 없든 전처럼 푼다.
테스트: 훅의 결과 불명 유지 it.each에 mapProblem 모양(VALIDATION_REJECTED +
선언 code, VALIDATION_REJECTED + 422 IDEMPOTENT_REQUEST_MISMATCH) 두 행을 더했다.
참조 페이지에서 422 재전송이 필드 오류와 다시 저장을 보인다던 테스트를, 결과
불명이 남고 확인이 보이는 테스트로 바꿨다. 리뷰가 요청한 대로 다시 마운트한 폼이
다른 값을 보이는 채 재전송해 422 IDEMPOTENT_REQUEST_MISMATCH를 받으면 결과
불명과 확인 버튼이 남는 테스트를 더했다.
버린 대안: kind 줄을 남기고 기능 선언 code만 빼기(실행기는 code가 선언인지
폼과 훅에 알리지 않는다).

위험·한계: 참조 기능처럼 problem details를 읽는 기능의 422 입력 검증은 재전송
뒤 결과 불명으로 남는다. 출구는 결과 불명 화면의 확인이다. 리뷰 실험 03-R1
X1~X3·X5는 그대로 키가 모두 key-1이어야 한다. CHANGELOG는 다음 커밋이 적는다.

검증: desktop batch에서 확인. node scripts/run-vitest.ts run
tests/component/application-mutation-admission.test.tsx
tests/features/reference-feature/reference-page.test.tsx
tests/component/form-foundation.test.tsx tests/unit/backend-envelope.test.ts,
리뷰 실험 03-R1 패치를 이 커밋에 적용

Refs: 1106/03-01 (final review FR-01)
2026-11-06 08:25:28 +09:00

1045 lines
37 KiB
TypeScript

// @vitest-environment jsdom
import { screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { createDemoSessionAdapter } from "../../../src/adapters/auth/external-session-adapter.ts";
import type {
ReferenceFeatureInput,
ReferenceResult,
} from "../../../src/features/reference-feature/application/reference-feature-api.ts";
import {
REFERENCE_RESOURCE_INVALIDATION_TOPIC,
REFERENCE_RESOURCE_QUERY_NAMESPACE,
} from "../../../src/features/reference-feature/contracts/reference-feature-contract.ts";
import { INVALIDATION_REGISTRY } from "../../../src/features/installed-feature-contracts.ts";
import type { ReferenceResourceView } from "../../../src/features/reference-feature/contracts/reference-mapper.ts";
import { createFailure } from "../../../src/contracts/errors.ts";
import { KO_MESSAGES } from "../../../src/presentation/i18n/catalog.ts";
import { inputWith, renderReference } from "./reference-page-harness.tsx";
/**
* 0929/08-02. The main area's text and accessible names with every ko-KR
* catalog value and every given data value cut out. The lint rule sees JSX
* text and attributes only; this also sees words passed through props.
*/
function mainTextOutsideCatalog(data: readonly string[]): string {
const main = screen.getByRole("main");
const names = [...main.querySelectorAll("[aria-label],[title],[placeholder],[alt]")]
.flatMap((element) =>
["aria-label", "title", "placeholder", "alt"].map(
(name) => element.getAttribute(name) ?? "",
),
);
return [...data, ...Object.values(KO_MESSAGES)]
.sort((left, right) => right.length - left.length)
.reduce(
(text, known) => text.split(known).join(" "),
[main.textContent ?? "", ...names].join(" "),
);
}
describe("reference feature page states", () => {
it("shows no Latin words outside the catalog on the ko-KR screens", async () => {
const resource = {
resourceId: "reference-1",
title: "Loaded",
createdAt: null,
};
const input = inputWith({
listResources: async () => ({ ok: true, value: [resource] }),
});
for (const [url, ready] of [
["/examples/reference-resources?limit=5&tags=open", "Loaded"],
["/examples/reference-resources/items/reference-1", "Detail"],
["/examples/reference-resources/new", "저장"],
["/examples/reference-resources/status", "목록으로 이동"],
] as const) {
const view = renderReference(input, url);
await screen.findAllByText(ready);
expect(
mainTextOutsideCatalog(["reference-1", "Loaded", "Detail", "open"]),
url,
).not.toMatch(/[A-Za-z]/);
view.unmount();
}
});
it("mounts list and detail keys under the installed governed namespace", async () => {
expect(REFERENCE_RESOURCE_QUERY_NAMESPACE).toEqual({
namespaceId: "reference-resource",
namespaceVersion: 1,
});
const installedEdge = INVALIDATION_REGISTRY.edges.find(
(edge) => edge.topicId === REFERENCE_RESOURCE_INVALIDATION_TOPIC,
);
expect(installedEdge?.namespace).toEqual(
REFERENCE_RESOURCE_QUERY_NAMESPACE,
);
const list = renderReference(inputWith());
await screen.findByRole("heading", { name: "표시할 항목이 없습니다." });
const listKey = list.client.getQueryCache().getAll()[0]?.queryKey;
expect(listKey?.slice(0, 4)).toEqual([
"query",
2,
REFERENCE_RESOURCE_QUERY_NAMESPACE.namespaceId,
REFERENCE_RESOURCE_QUERY_NAMESPACE.namespaceVersion,
]);
list.unmount();
const detail = renderReference(
inputWith(),
"/examples/reference-resources/items/reference-1",
);
await screen.findByText("Detail");
const detailKey = detail.client.getQueryCache().getAll()[0]?.queryKey;
expect(detailKey?.slice(0, 4)).toEqual([
"query",
2,
installedEdge?.namespace.namespaceId,
installedEdge?.namespace.namespaceVersion,
]);
detail.unmount();
});
it("renders loading, success and empty states through the installed route", async () => {
let resolveList:
| ((result: ReferenceResult<readonly ReferenceResourceView[]>) => void)
| undefined;
const pending = new Promise<
ReferenceResult<readonly ReferenceResourceView[]>
>((resolve) => {
resolveList = resolve;
});
const loaded = renderReference(
inputWith({ listResources: async () => pending }),
);
expect(await screen.findByLabelText("불러오는 중")).toBeVisible();
resolveList?.({
ok: true,
value: [
{
resourceId: "reference-1",
title: "Loaded",
createdAt: null,
},
],
});
expect(await screen.findByText("Loaded")).toBeVisible();
loaded.unmount();
renderReference(inputWith(), "/examples/reference-resources?limit=10");
expect(
await screen.findByRole("heading", {
name: "표시할 항목이 없습니다.",
}),
).toBeVisible();
});
it("rejects invalid URL input before the feature application input", async () => {
const listResources = vi.fn();
renderReference(
inputWith({ listResources }),
"/examples/reference-resources?limit=invalid",
);
expect(
await screen.findByRole("heading", {
name: "올바르지 않은 주소입니다.",
}),
).toBeVisible();
expect(listResources).not.toHaveBeenCalled();
});
// 08-09. The count is a status only once there is a result to count.
it("shows the result count only for a loaded list", async () => {
const resultCount = () =>
document.querySelector(".collection-page__result-count");
let resolveList:
| ((result: ReferenceResult<readonly ReferenceResourceView[]>) => void)
| undefined;
const loading = renderReference(
inputWith({
listResources: () =>
new Promise((resolve) => {
resolveList = resolve;
}),
}),
);
expect(await screen.findByLabelText("불러오는 중")).toBeVisible();
expect(resultCount()).toBeNull();
resolveList?.({
ok: true,
value: [{ resourceId: "reference-1", title: "Loaded", createdAt: null }],
});
expect(await screen.findByText("Loaded")).toBeVisible();
expect(resultCount()).toHaveTextContent("총 1개 항목");
loading.unmount();
renderReference(
inputWith({
listResources: async () => ({
ok: false,
error: createFailure("SERVER_FAILURE", "LIST_REFERENCE_RESOURCES", 0),
}),
}),
);
expect(await screen.findByRole("alert")).toHaveTextContent(
"요청을 완료하지 못했습니다.",
);
expect(resultCount()).toBeNull();
});
// 08-13. A server id equal to a static segment still opens its detail.
it.each(["new", "status"])(
"opens the detail screen for an item whose id is %s",
async (resourceId) => {
const user = userEvent.setup();
const getResource = vi.fn(async (id: string) => ({
ok: true as const,
value: { resourceId: id, title: "Detail", createdAt: null },
}));
renderReference(
inputWith({
listResources: async () => ({
ok: true,
value: [
{ resourceId, title: `Item ${resourceId}`, createdAt: null },
],
}),
getResource,
}),
);
await user.click(
await screen.findByRole("link", { name: `Item ${resourceId}` }),
);
expect(
await screen.findByRole("heading", { level: 1, name: "Detail" }),
).toBeVisible();
expect(getResource.mock.calls[0]?.[0]).toBe(resourceId);
},
);
it("renders backend forbidden even when the client access hint allowed entry", async () => {
const user = userEvent.setup();
renderReference(
inputWith({
listResources: async () => ({
ok: false,
error: createFailure(
"FORBIDDEN",
"LIST_REFERENCE_RESOURCES",
0,
),
}),
}),
);
expect(await screen.findByRole("alert")).toHaveTextContent(
"접근할 수 없습니다.",
);
await user.click(
screen.getByRole("button", { name: "안전한 화면으로 이동" }),
);
expect(
await screen.findByRole("heading", {
level: 1,
name: "Clean Architecture Frontend",
}),
).toBeVisible();
});
it("starts sign-in with the current route for a backend auth failure", async () => {
const user = userEvent.setup();
const demoSession = createDemoSessionAdapter("authenticated");
const beginSignIn = vi.fn(async () => {});
const session = { ...demoSession, beginSignIn };
renderReference(
inputWith({
listResources: async () => ({
ok: false,
error: createFailure(
"AUTH_REQUIRED",
"LIST_REFERENCE_RESOURCES",
0,
),
}),
}),
"/examples/reference-resources?limit=5",
session,
);
await user.click(await screen.findByRole("button", { name: "로그인 시작" }));
expect(beginSignIn).toHaveBeenCalledWith(
"/examples/reference-resources?limit=5",
);
});
it("falls back to a public route when starting sign-in fails", async () => {
const user = userEvent.setup();
const demoSession = createDemoSessionAdapter("authenticated");
const beginSignIn = vi.fn(async () => {
throw new Error("identity provider unavailable");
});
renderReference(
inputWith({
listResources: async () => ({
ok: false,
error: createFailure(
"AUTH_REQUIRED",
"LIST_REFERENCE_RESOURCES",
0,
),
}),
}),
"/examples/reference-resources?limit=5",
{ ...demoSession, beginSignIn },
);
await user.click(await screen.findByRole("button", { name: "로그인 시작" }));
expect(
await screen.findByRole("heading", {
level: 1,
name: "Clean Architecture Frontend",
}),
).toBeVisible();
});
it("deduplicates create, preserves input and surfaces a conflict", async () => {
const user = userEvent.setup();
let finish:
| ((result: ReferenceResult<ReferenceResourceView>) => void)
| undefined;
const createResource = vi.fn(
() =>
new Promise<ReferenceResult<ReferenceResourceView>>((resolve) => {
finish = resolve;
}),
);
renderReference(
inputWith({ createResource }),
"/examples/reference-resources/new",
);
await screen.findByRole("heading", {
name: "Reference resource 만들기",
});
await user.type(
screen.getByRole("textbox", { name: /새 항목 이름/ }),
"Conflicting",
);
await user.type(screen.getByLabelText("설명"), "Keep this input");
const submit = screen.getByRole("button", { name: "저장" });
await user.dblClick(submit);
await waitFor(() => expect(createResource).toHaveBeenCalledOnce());
// 1103/08-02. Busy, not disabled: a disabled button drops keyboard focus
// to the body. The second click is refused by the form, not the button.
const saving = screen.getByRole("button", { name: "저장 중…" });
expect(saving).toHaveAttribute("aria-busy", "true");
expect(saving).toHaveFocus();
finish?.({
ok: false,
error: createFailure(
"CONFLICT",
"CREATE_REFERENCE_RESOURCE",
0,
{ effect: "NOT_APPLIED" },
),
});
expect(await screen.findByText(/다른 변경과 충돌했습니다/)).toBeVisible();
expect(
screen.getByRole("textbox", { name: /새 항목 이름/ }),
).toHaveValue("Conflicting");
expect(screen.getByLabelText("설명")).toHaveValue("Keep this input");
});
it("blocks a new save and resends an unknown create with the same key", async () => {
const user = userEvent.setup();
const createResource = vi
.fn<ReferenceFeatureInput["createResource"]>()
.mockResolvedValueOnce({
ok: false,
error: createFailure(
"SERVER_FAILURE",
"CREATE_REFERENCE_RESOURCE",
0,
{ effect: "MAYBE_APPLIED" },
),
})
.mockResolvedValue({
ok: true,
value: { resourceId: "created", title: "Unknown result", createdAt: null },
});
renderReference(
inputWith({ createResource }),
"/examples/reference-resources/new",
);
const name = await screen.findByRole("textbox", { name: /새 항목 이름/ });
await user.type(name, "Unknown result");
await user.click(screen.getByRole("button", { name: "저장" }));
expect(
await screen.findByText("변경 결과를 확인할 수 없습니다."),
).toBeVisible();
expect(screen.getByRole("button", { name: "저장" })).toBeDisabled();
expect(
screen.queryByText("저장하지 못했습니다. 잠시 후 다시 시도해 주세요."),
).not.toBeInTheDocument();
// No path lets the user declare "not applied" without evidence.
expect(
screen.queryByRole("button", { name: "변경되지 않음으로 확인" }),
).not.toBeInTheDocument();
// 16-04. Built by the route codec, so the link is already the canonical
// URL the router would redirect to (the default limit is written out).
expect(
screen.getByRole("link", { name: "목록을 새로 불러와 확인" }),
).toHaveAttribute("href", "/examples/reference-resources?limit=20");
await user.click(screen.getByRole("button", { name: "저장" }));
expect(createResource).toHaveBeenCalledOnce();
expect(name).toHaveValue("Unknown result");
await user.click(
screen.getByRole("button", { name: "같은 요청으로 다시 보내기" }),
);
expect(await screen.findByRole("status")).toHaveTextContent("저장했습니다.");
expect(createResource).toHaveBeenCalledTimes(2);
const [first, second] = createResource.mock.calls;
expect(second?.[0]).toEqual(first?.[0]);
expect(first?.[1]?.intent?.idempotencyKey).toBe("reference-page-key-1");
expect(second?.[1]?.intent?.idempotencyKey).toBe("reference-page-key-1");
expect(name).toHaveValue("");
});
/**
* 1106/03-01 (D10 supplement). The form is never held for good after a
* same-key resend. A refusal that may change (429) keeps the result
* unknown and the confirm and resend actions on screen. So does a 422
* (final review FR-01): this feature's gateway reads every 422 as a field
* error whatever its code, and only the paired backend's own table codes
* settle a resent request.
*/
async function resendAnUnknownCreate(resendAnswer: ReferenceResult<ReferenceResourceView>) {
const user = userEvent.setup();
const createResource = vi
.fn<ReferenceFeatureInput["createResource"]>()
.mockResolvedValueOnce({
ok: false,
error: createFailure("SERVER_FAILURE", "CREATE_REFERENCE_RESOURCE", 0, {
effect: "MAYBE_APPLIED",
}),
})
.mockResolvedValueOnce(resendAnswer)
.mockResolvedValue({
ok: true,
value: { resourceId: "created", title: "Resent", createdAt: null },
});
renderReference(
inputWith({ createResource }),
"/examples/reference-resources/new",
);
const name = await screen.findByRole("textbox", { name: /새 항목 이름/ });
await user.type(name, "Resent");
await user.click(screen.getByRole("button", { name: "저장" }));
await user.click(
await screen.findByRole("button", { name: "같은 요청으로 다시 보내기" }),
);
await waitFor(() => expect(createResource).toHaveBeenCalledTimes(2));
return { user, name, createResource };
}
it("keeps the confirm on screen when the resend is refused for now", async () => {
const { user } = await resendAnUnknownCreate({
ok: false,
error: createFailure("RATE_LIMITED", "CREATE_REFERENCE_RESOURCE", 0, {
effect: "NOT_APPLIED",
httpStatus: 429,
}),
});
expect(
await screen.findByText(KO_MESSAGES["form.resendLater"]),
).toBeVisible();
expect(screen.getByText("변경 결과를 확인할 수 없습니다.")).toBeVisible();
expect(screen.getByRole("button", { name: "같은 요청으로 다시 보내기" })).toBeVisible();
await user.click(screen.getByRole("button", { name: "변경됨으로 확인" }));
expect(await screen.findByText("저장했습니다.")).toBeVisible();
});
it("keeps the confirm on screen when the resend is refused with a 422", async () => {
const { user, name } = await resendAnUnknownCreate({
ok: false,
error: createFailure("VALIDATION_REJECTED", "CREATE_REFERENCE_RESOURCE", 0, {
code: "REFERENCE_RESOURCE_REJECTED",
effect: "NOT_APPLIED",
httpStatus: 422,
validationIssues: [{ path: "name", code: "REQUIRED" }],
}),
});
expect(
await screen.findByText(KO_MESSAGES["form.resendLater"]),
).toBeVisible();
expect(screen.getByText("변경 결과를 확인할 수 없습니다.")).toBeVisible();
expect(name).not.toHaveAttribute("aria-invalid");
expect(screen.getByRole("button", { name: "저장" })).toBeDisabled();
await user.click(screen.getByRole("button", { name: "변경됨으로 확인" }));
expect(await screen.findByText("저장했습니다.")).toBeVisible();
});
it.each([
["AUTH_REQUIRED", "계속하려면 로그인이 필요합니다.", "로그인"],
["FORBIDDEN", "이 작업을 수행할 권한이 없습니다.", "안전한 화면으로 이동"],
["RATE_LIMITED", "요청이 많습니다. 잠시 후 다시 시도해 주세요.", "다시 시도"],
] as const)(
"gives a %s create failure its own copy and action",
async (kind, copy, action) => {
const user = userEvent.setup();
const demoSession = createDemoSessionAdapter("authenticated");
const beginSignIn = vi.fn(async () => {});
const createResource = vi.fn(async () => ({
ok: false as const,
error: createFailure(kind, "CREATE_REFERENCE_RESOURCE", 0, {
effect: "NOT_APPLIED",
}),
}));
renderReference(
inputWith({ createResource }),
"/examples/reference-resources/new",
{ ...demoSession, beginSignIn },
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"Rejected",
);
await user.click(screen.getByRole("button", { name: "저장" }));
expect(await screen.findByRole("alert")).toHaveTextContent(copy);
expect(document.body).not.toHaveTextContent("입력 내용을 확인해 주세요.");
expect(
screen.queryByText("변경 결과를 확인할 수 없습니다."),
).not.toBeInTheDocument();
await user.click(screen.getByRole("button", { name: action }));
if (kind === "AUTH_REQUIRED") {
expect(beginSignIn).toHaveBeenCalledWith(
"/examples/reference-resources/new",
);
} else if (kind === "FORBIDDEN") {
// Leaving still passes the dirty-input guard.
await user.click(
await screen.findByRole("button", { name: "변경 버리고 이동" }),
);
expect(
await screen.findByRole("heading", {
level: 1,
name: "Clean Architecture Frontend",
}),
).toBeVisible();
} else {
await waitFor(() => expect(createResource).toHaveBeenCalledTimes(2));
}
},
);
/**
* 1103/08-02. A keyboard save whose failure is not a field error used to
* leave focus on a button the result disables, so the browser dropped it
* to the body. Focus now moves to the failure status above the form, and
* one Tab reaches its first recovery action.
*/
it.each([
{
result: "unknown",
failure: createFailure("SERVER_FAILURE", "CREATE_REFERENCE_RESOURCE", 0, {
effect: "MAYBE_APPLIED",
}),
text: "변경 결과를 확인할 수 없습니다.",
firstAction: "변경됨으로 확인",
},
{
result: "rate-limited",
failure: createFailure("RATE_LIMITED", "CREATE_REFERENCE_RESOURCE", 0, {
effect: "NOT_APPLIED",
httpStatus: 429,
}),
text: "요청이 많습니다. 잠시 후 다시 시도해 주세요.",
firstAction: "다시 시도",
},
])("moves focus to the failure status after a keyboard save ($result)", async ({
failure,
text,
firstAction,
}) => {
const user = userEvent.setup();
renderReference(
inputWith({ createResource: async () => ({ ok: false, error: failure }) }),
"/examples/reference-resources/new",
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"Keyboard save",
);
screen.getByRole("button", { name: "저장" }).focus();
await user.keyboard("{Enter}");
const status = (await screen.findByText(text)).closest(
".page-template__feedback",
);
await waitFor(() => expect(status).toHaveFocus());
await user.tab();
expect(screen.getByRole("button", { name: firstAction })).toHaveFocus();
});
/**
* 1105/08-01. A recovery action goes away with its status once it has
* done its work, so the browser dropped focus to the body. Focus now stays
* in the feedback area that shows the result.
*/
it.each([
{
action: "변경됨으로 확인",
tabs: 1,
failure: createFailure("SERVER_FAILURE", "CREATE_REFERENCE_RESOURCE", 0, {
effect: "MAYBE_APPLIED",
}),
text: "변경 결과를 확인할 수 없습니다.",
},
{
action: "같은 요청으로 다시 보내기",
tabs: 2,
failure: createFailure("SERVER_FAILURE", "CREATE_REFERENCE_RESOURCE", 0, {
effect: "MAYBE_APPLIED",
}),
text: "변경 결과를 확인할 수 없습니다.",
},
{
action: "다시 시도",
tabs: 1,
failure: createFailure("RATE_LIMITED", "CREATE_REFERENCE_RESOURCE", 0, {
effect: "NOT_APPLIED",
httpStatus: 429,
}),
text: "요청이 많습니다. 잠시 후 다시 시도해 주세요.",
},
])("keeps focus in the feedback after '$action' from the keyboard", async ({
action,
tabs,
failure,
text,
}) => {
const user = userEvent.setup();
const createResource = vi
.fn<ReferenceFeatureInput["createResource"]>()
.mockResolvedValueOnce({ ok: false, error: failure })
.mockResolvedValue({
ok: true,
value: { resourceId: "created", title: "Keyboard save", createdAt: null },
});
renderReference(
inputWith({ createResource }),
"/examples/reference-resources/new",
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"Keyboard save",
);
screen.getByRole("button", { name: "저장" }).focus();
await user.keyboard("{Enter}");
const status = (await screen.findByText(text)).closest(
".page-template__feedback",
);
await waitFor(() => expect(status).toHaveFocus());
for (let tab = 0; tab < tabs; tab += 1) await user.tab();
expect(screen.getByRole("button", { name: action })).toHaveFocus();
await user.keyboard("{Enter}");
const saved = await screen.findByText("저장했습니다.");
await waitFor(() =>
expect(saved.closest(".page-template__feedback")).toHaveFocus(),
);
});
// 1105/08-04. A save left running when the user leaves and comes back
// still holds the coordinator. The remounted form says a save is running
// and keeps its save off, instead of a save button that does nothing.
it("says a save is running and keeps the save off after coming back during a save", async () => {
const user = userEvent.setup();
let release:
| ((result: ReferenceResult<ReferenceResourceView>) => void)
| undefined;
const createResource = vi
.fn<ReferenceFeatureInput["createResource"]>()
.mockImplementationOnce(
() =>
new Promise<ReferenceResult<ReferenceResourceView>>((resolve) => {
release = resolve;
}),
)
.mockResolvedValue({
ok: true,
value: { resourceId: "created-2", title: "Second item", createdAt: null },
});
renderReference(
inputWith({ createResource }),
"/examples/reference-resources/new",
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"First item",
);
await user.click(screen.getByRole("button", { name: "저장" }));
await waitFor(() => expect(createResource).toHaveBeenCalledOnce());
await user.click(screen.getByRole("button", { name: "목록으로 돌아가기" }));
await waitFor(() =>
expect(window.location.pathname).toBe("/examples/reference-resources"),
);
window.history.pushState({}, "", "/examples/reference-resources/new");
window.dispatchEvent(new PopStateEvent("popstate"));
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"Second item",
);
expect(await screen.findByText("변경 사항을 저장하고 있습니다.")).toBeVisible();
expect(screen.getByRole("button", { name: "저장" })).toBeDisabled();
release?.({
ok: true,
value: { resourceId: "created-1", title: "First item", createdAt: null },
});
await waitFor(() =>
expect(screen.getByRole("button", { name: "저장" })).toBeEnabled(),
);
expect(screen.queryByText("변경 사항을 저장하고 있습니다.")).not.toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "저장" }));
expect(await screen.findByText("저장했습니다.")).toBeVisible();
expect(createResource).toHaveBeenCalledTimes(2);
});
/**
* 1106/08-01. The form the user came back to did not start the save
* still running, and holds none of its result (review probe 08-R1).
*/
async function leaveDuringSaveAndComeBack(
...laterAnswers: readonly ReferenceResult<ReferenceResourceView>[]
) {
const user = userEvent.setup();
let release:
| ((result: ReferenceResult<ReferenceResourceView>) => void)
| undefined;
const createResource = vi
.fn<ReferenceFeatureInput["createResource"]>()
.mockImplementationOnce(
() =>
new Promise<ReferenceResult<ReferenceResourceView>>((resolve) => {
release = resolve;
}),
);
for (const answer of laterAnswers) createResource.mockResolvedValueOnce(answer);
renderReference(
inputWith({ createResource }),
"/examples/reference-resources/new",
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"First item",
);
await user.click(screen.getByRole("button", { name: "저장" }));
await waitFor(() => expect(createResource).toHaveBeenCalledOnce());
await user.click(screen.getByRole("button", { name: "목록으로 돌아가기" }));
await waitFor(() =>
expect(window.location.pathname).toBe("/examples/reference-resources"),
);
window.history.pushState({}, "", "/examples/reference-resources/new");
window.dispatchEvent(new PopStateEvent("popstate"));
expect(await screen.findByText("변경 사항을 저장하고 있습니다.")).toBeVisible();
return {
user,
createResource,
release(result: ReferenceResult<ReferenceResourceView>) {
release?.(result);
},
};
}
// 1106/03-01 (final review FR-01). The remounted form shows other values
// than the save it did not start; its resend sends that save, with its
// key. A 422 IDEMPOTENT_REQUEST_MISMATCH there says the key already
// reached the server, so the first request may have applied: it stays
// unknown and the confirm stays on screen.
it("keeps a resent request unknown on a remounted form when the server answers 422 IDEMPOTENT_REQUEST_MISMATCH", async () => {
const { user, createResource, release } = await leaveDuringSaveAndComeBack({
ok: false,
error: createFailure("VALIDATION_REJECTED", "CREATE_REFERENCE_RESOURCE", 0, {
code: "IDEMPOTENT_REQUEST_MISMATCH",
effect: "NOT_APPLIED",
httpStatus: 422,
}),
});
release({
ok: false,
error: createFailure("SERVER_FAILURE", "CREATE_REFERENCE_RESOURCE", 0, {
effect: "MAYBE_APPLIED",
}),
});
await screen.findByRole("button", { name: "같은 요청으로 다시 보내기" });
await user.type(
screen.getByRole("textbox", { name: /새 항목 이름/ }),
"Second item",
);
await user.click(
screen.getByRole("button", { name: "같은 요청으로 다시 보내기" }),
);
await waitFor(() => expect(createResource).toHaveBeenCalledTimes(2));
expect(
await screen.findByText(KO_MESSAGES["form.resendLater"]),
).toBeVisible();
expect(screen.getByText("변경 결과를 확인할 수 없습니다.")).toBeVisible();
expect(screen.getByRole("button", { name: "변경됨으로 확인" })).toBeVisible();
const [first, second] = createResource.mock.calls;
expect(second?.[0]).toEqual(first?.[0]);
expect(second?.[1]?.intent?.idempotencyKey).toBe(
first?.[1]?.intent?.idempotencyKey,
);
});
// 1106/08-01 (A). Confirming that save from the remounted form used to
// show nothing and drop focus to the body: the form had no submitted
// values to settle.
it("shows the save confirmed on a remounted form and keeps focus in its feedback", async () => {
const { user, release } = await leaveDuringSaveAndComeBack();
release({
ok: false,
error: createFailure("SERVER_FAILURE", "CREATE_REFERENCE_RESOURCE", 0, {
effect: "MAYBE_APPLIED",
}),
});
const confirm = await screen.findByRole("button", { name: "변경됨으로 확인" });
confirm.focus();
await user.keyboard("{Enter}");
const saved = await screen.findByText("저장했습니다.");
await waitFor(() =>
expect(saved.closest(".page-template__feedback")).toHaveFocus(),
);
});
// 1106/08-01, diff review. What the user typed on the remounted form was
// never sent. Confirming the earlier save shows that save and leaves the
// new input, and its leave guard, in place.
it("keeps what the user typed on a remounted form when confirming the earlier save", async () => {
const { user, release } = await leaveDuringSaveAndComeBack();
release({
ok: false,
error: createFailure("SERVER_FAILURE", "CREATE_REFERENCE_RESOURCE", 0, {
effect: "MAYBE_APPLIED",
}),
});
await screen.findByRole("button", { name: "변경됨으로 확인" });
const name = screen.getByRole("textbox", { name: /새 항목 이름/ });
await user.type(name, "Second item");
screen.getByRole("button", { name: "변경됨으로 확인" }).focus();
await user.keyboard("{Enter}");
const saved = await screen.findByText("저장했습니다.");
await waitFor(() =>
expect(saved.closest(".page-template__feedback")).toHaveFocus(),
);
expect(name).toHaveValue("Second item");
await user.click(screen.getByRole("button", { name: "목록으로 돌아가기" }));
expect(
await screen.findByRole("button", { name: "변경 버리고 이동" }),
).toBeVisible();
});
// 1106/08-01 (B). That save succeeding left the remounted form saying
// nothing. The form cannot know its result, so it points to the list.
it("points to the list once a save the remounted form did not start ends", async () => {
const { release } = await leaveDuringSaveAndComeBack();
release({
ok: true,
value: { resourceId: "created-1", title: "First item", createdAt: null },
});
expect(
await screen.findByRole("link", { name: "목록을 새로 불러와 확인" }),
).toBeVisible();
expect(screen.queryByText("변경 사항을 저장하고 있습니다.")).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "저장" })).toBeEnabled();
});
// 0929/08-04. The ids a user quotes to support reach the screens that
// need them, and the sample status page shows no made-up reference.
it("shows the request id of an unknown create next to its result", async () => {
const user = userEvent.setup();
renderReference(
inputWith({
createResource: async () => ({
ok: false,
error: createFailure("SERVER_FAILURE", "CREATE_REFERENCE_RESOURCE", 0, {
effect: "MAYBE_APPLIED",
requestId: "corr-save-500",
}),
}),
}),
"/examples/reference-resources/new",
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"Unknown result",
);
await user.click(screen.getByRole("button", { name: "저장" }));
expect(await screen.findByText("변경 결과를 확인할 수 없습니다.")).toBeVisible();
expect(screen.getByText("지원 참조: corr-save-500")).toBeVisible();
});
it("carries a failure's request id to the support status page", async () => {
const user = userEvent.setup();
renderReference(
inputWith({
listResources: async () => ({
ok: false,
error: createFailure("UNKNOWN_CLIENT_FAILURE", "LIST_REFERENCE_RESOURCES", 0, {
requestId: "corr-list-400",
}),
}),
}),
);
await user.click(await screen.findByRole("button", { name: "지원 정보 확인" }));
expect(
await screen.findByRole("heading", { level: 1, name: "잠시 사용할 수 없습니다." }),
).toBeVisible();
expect(screen.getByText("지원 참조: corr-list-400")).toBeVisible();
expect(document.body).not.toHaveTextContent("REFERENCE-STATUS-DEMO");
});
it("shows no support reference on a status page opened directly", async () => {
renderReference(inputWith(), "/examples/reference-resources/status");
expect(
await screen.findByRole("heading", { level: 1, name: "잠시 사용할 수 없습니다." }),
).toBeVisible();
expect(document.body).not.toHaveTextContent("지원 참조");
});
it("settles the form after confirming an unknown create was applied", async () => {
const user = userEvent.setup();
const createResource = vi.fn(async () => ({
ok: false as const,
error: createFailure(
"SERVER_FAILURE",
"CREATE_REFERENCE_RESOURCE",
0,
{ effect: "MAYBE_APPLIED" },
),
}));
renderReference(
inputWith({ createResource }),
"/examples/reference-resources/new",
);
const name = await screen.findByRole("textbox", {
name: /새 항목 이름/,
});
await user.type(name, "Already created");
await user.click(screen.getByRole("button", { name: "저장" }));
await user.click(
await screen.findByRole("button", { name: "변경됨으로 확인" }),
);
expect(await screen.findByRole("status")).toHaveTextContent("저장했습니다.");
expect(name).toHaveValue("");
await user.click(screen.getByRole("button", { name: "저장" }));
expect(createResource).toHaveBeenCalledOnce();
});
it("treats an applied-confirmed failure as a settled create", async () => {
const user = userEvent.setup();
const createResource = vi.fn(async () => ({
ok: false as const,
error: createFailure(
"SERVER_FAILURE",
"CREATE_REFERENCE_RESOURCE",
0,
{ effect: "APPLIED_CONFIRMED" },
),
}));
renderReference(
inputWith({ createResource }),
"/examples/reference-resources/new",
);
const name = await screen.findByRole("textbox", {
name: /새 항목 이름/,
});
await user.type(name, "Committed despite response");
await user.click(screen.getByRole("button", { name: "저장" }));
expect(await screen.findByRole("status")).toHaveTextContent("저장했습니다.");
expect(name).toHaveValue("");
expect(
screen.queryByText("저장하지 못했습니다. 잠시 후 다시 시도해 주세요."),
).not.toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "저장" }));
expect(createResource).toHaveBeenCalledOnce();
});
it("keeps stale data visible during refresh failure and recovers on retry", async () => {
const user = userEvent.setup();
const listResources = vi
.fn<ReferenceFeatureInput["listResources"]>()
.mockResolvedValueOnce({
ok: true,
value: [
{
resourceId: "existing",
title: "Existing",
createdAt: null,
},
],
})
.mockResolvedValueOnce({
ok: false,
error: createFailure(
"SERVER_FAILURE",
"LIST_REFERENCE_RESOURCES",
0,
),
})
.mockResolvedValue({
ok: true,
value: [
{
resourceId: "recovered",
title: "Recovered",
createdAt: null,
},
],
});
renderReference(inputWith({ listResources }));
await screen.findByText("Existing");
await user.click(screen.getByRole("button", { name: "새로고침" }));
expect(
await screen.findByText("기존 정보를 표시하고 있습니다."),
).toBeVisible();
expect(screen.getByText("Existing")).toBeVisible();
await user.click(screen.getByRole("button", { name: "다시 시도" }));
expect(await screen.findByText("Recovered")).toBeVisible();
await waitFor(() =>
expect(screen.queryByText("stale-degraded")).not.toBeInTheDocument(),
);
expect(listResources).toHaveBeenCalledTimes(3);
});
});