Files
clean-architecture-frontend…/tests/features/reference-feature/reference-page.test.tsx
T
DongHyeonka f2b8ba75d3 fix(forms): 다른 저장이 진행 중이면 저장 버튼을 끄고 진행 문구를 보인다
문제
1103/08-02 수정(2d5d41f8)이 저장 버튼을 disabled 대신 pending으로 바꾸면서
버튼은 결과 불명일 때만 꺼진다. 코디네이터가 mutation-pending이어도 이 폼이
저장 중이 아닐 수 있다. 저장 중에 화면을 떠났다가 같은 세션에서 돌아온 경우
(진행 중 시도가 있는 동안 채널이 남는다)와 "변경됨으로 확인"을 처리하는
동안이다. 그때 onSubmit은 아무것도 하지 않고 돌아가고 feedback에도 아무것도
없다. 저장을 눌러도 반응이 없고, 첫 저장이 끝난 뒤에도 그 클릭은 실행되지
않는다(리뷰 08-R1 D). 참조 폼과 생성기 템플릿이 같다.

고른 방법
"코디네이터가 mutation-pending인데 이 폼은 저장 중이 아님"을 otherSaveRunning으로
두고 두 가지를 함께 한다.
- 저장 버튼을 그동안 끈다. 이 폼 자신의 저장 중에는 지금처럼 끄지 않고 busy로
  둔다(포커스 유지, 1103/08-02). 그때 포커스는 저장 버튼에 있지 않다(다시
  마운트한 폼이거나, 누른 버튼은 "변경됨으로 확인"이다).
- feedback에 코디네이터 상태를 AsyncSurface로 그려 "변경 사항을 저장하고
  있습니다."를 보인다. 이 폼의 결과 불명을 확인하는 동안(결과가 effect-unknown)은
  그리지 않는다. 확인이 끝나면 곧 결과가 바뀌고, 그 사이에 상태 문구가 하나 더
  생기지 않게 한다.
참조 폼 페이지와 create:feature 쓰기 슬라이스 템플릿을 같이 고쳤다.

버린 대안
문구만 보이고 버튼은 켜 둔다(리뷰 문서가 포커스 때문에 권한 쪽): 확인 중에는
문구를 그릴 수 없어(위) 그때 버튼이 다시 무반응이 된다. 끄는 버튼에 포커스가
없으므로 포커스를 잃지 않는다.

위험·한계
- 생성기 쪽은 생성 결과 문자열만 단위 테스트가 본다. 다시 마운트하는 동작은
  참조 폼 테스트로만 확인한다. 생성 기능의 기존 테스트는 test:feature-scaffold
  (FE-GATE-020)와 test:sample-removal에서 돈다.
- 다른 탭이나 새로고침은 해당 없다(코디네이터는 앱 메모리 안이다).

검증
desktop batch에서 확인:
node scripts/run-vitest.ts run tests/features/reference-feature/reference-page.test.tsx
tests/unit/create-feature.test.ts

Refs: 1105/08-04
2026-11-06 02:33:16 +09:00

811 lines
28 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("");
});
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);
});
// 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);
});
});