문제: `check:i18n`은 화면 파일 전체에 `/[가-힣]/`를 돌린다. 한국어 주석
한 줄에 실패하고, 영어 JSX 문구와 영어 접근성 이름은 통과한다. 샘플
화면에도 영어 literal이 이미 있었다(목록 h1 "Reference feature",
`limit {n}`, 목록 aria-label, 상세 "DetailPage"·"Resource ID"·"Created",
폼·상태 eyebrow). ko-KR 사용자에게 영어 문구와 스크린리더 이름이 섞인다.
고른 방법: (B) 문구 literal 검사를 ESLint `no-restricted-syntax` 선택자로
옮긴다(`eslint.config.ts`의 `screenTextSelectors`).
- 대상: 글자(`\p{L}`)가 든 `JSXText`, 표시·접근성 속성(`aria-label`,
`aria-description`, `aria-roledescription`, `aria-valuetext`,
`aria-placeholder`, `title`, `placeholder`, `alt`, `label`)의 문자열
literal, 그리고 `{"..."}` 형태의 같은 literal. 주석은 AST에 없어 빠진다.
구두점·숫자만 있는 문구는 통과한다.
- 범위(4.3절 "화면 코드"): 지난 `check:i18n`과 같은 폴더다. 공통 UI
폴더와 `src/features/*/presentation`. 컴포넌트 갤러리
`src/presentation/examples`는 지금처럼 뺀다. stories(`*.stories.tsx`)는
workshop 코드라 뺀다. 테스트는 이 폴더 밖이라 대상이 아니다.
- 이 항목은 일반 `no-restricted-syntax` 목록을 대체하므로 FE-OC-019
선택자(raw HTML, script 생성)를 함께 싣는다.
- `check:i18n`에는 catalog parity와 raw backend 메시지 검사만 남긴다.
raw HTML은 원래 전역 FE-OC-019 ESLint 규칙이 거절한다.
- `check:i18n:fixture`는 ESLint Node API로 같은 규칙을 fixture 트리에도
돌린다. forbidden 파일은 하나하나 거절돼야 하고(아니면 종료 코드 2),
새 `tests/fixtures/i18n/allowed` 트리(한국어 주석, 구두점, catalog
문구)는 통과해야 한다(거절되면 종료 코드 2). 게이트 기대값(종료 1,
"I18n contract failed:")은 그대로다.
- fixture 추가: allowed `korean-comment.tsx`, forbidden
`english-jsx-text.tsx`, `english-accessible-name.tsx`.
- 샘플의 영어 literal 11곳을 catalog로 옮겼다. 새 키 10개
(`reference.list.title`·`filterLimit`·`filterTags`·`resources`,
`reference.detail.eyebrow`·`titlePending`·`resourceId`·`createdAt`,
`reference.form.eyebrow`, `reference.status.eyebrow`). en-US 값은
예전 영어 문구 그대로라 en-US 화면은 바뀌지 않는다. ko-KR 화면은 한국어가
된다.
버린 대안:
- (A) 현 상태: 두 제품이 각각 막히거나 스크립트를 고쳤다.
- (C) "행동·상태 문구"만 정규식으로 고르는 제품 정책: 한국어 문장 목록에
기대 영어를 못 잡고, 템플릿 기본값으로 쓰기에 제품 특화다.
ESLint 설정은 제품이 자기 규칙으로 덮어쓸 수 있는 자리다(한 locale 제품,
고유명사 허용).
위험·한계:
- 식 안에서 만든 문구는 보지 못한다. template literal, 삼항식, 객체
prop(`heading.title` 같은 것)이 그렇다. 샘플의 이런 문구는 손으로
옮겼고, `reference-page.test.tsx`가 ko-KR main 영역을 catalog·데이터
밖 라틴 문자로 검사해 그 빈 곳을 샘플에서만 막는다.
- 고유명사·브랜드 이름도 걸린다. 제품이 선택자를 덮어쓰거나 그 줄에
`eslint-disable-next-line`을 쓴다.
- ko-KR route 제목(`route.REFERENCE_RESOURCE_*`)은 catalog 안의 영어라
그대로 뒀다(라우트 제목 정리는 0929/08-06 몫).
- `tests/e2e/reference-form.spec.ts`의 ko-KR 목록 h1 기대값을 "참조
기능"으로 바꿨다. e2e는 이 worktree에서 돌리지 않았다(webServer가
pnpm build를 부른다).
- 시각 골든(`tests/visual`)은 /examples/ui·states·platform만 찍는다.
샘플 화면과 nav 문구는 바뀌지 않아 골든 영향이 없다고 본다(미실행).
검증:
- RED(수정 전):
- E1 한글 주석 변이: `node scripts/check-i18n.ts` -> "hardcoded common
user-facing locale literal in .../reference-resource-status-page.tsx",
exit 1
- E1b 영어 JSX 문구 변이: `check-i18n.ts` PASS exit 0, `eslint` exit 0
- `check-i18n.ts --fixture` -> "I18n fixture was not rejected:
english-accessible-name.tsx, english-jsx-text.tsx", exit 2
- 새 ko-KR main 테스트: "limit 5 · tags ..." 가 남아 실패
- GREEN(수정 후):
- E1 변이: `check-i18n.ts` PASS, `eslint` exit 0
- E1b 변이: `eslint` -> 42:13 no-restricted-syntax, exit 1
- `check-i18n.ts` PASS(224 keys), `--fixture` -> forbidden 7개 모두
거절, "I18n contract failed:", exit 1. allowed에 영어 문구를 넣으면
"I18n allowed fixture was rejected", exit 2
- ko-KR main 테스트 통과
- `npx eslint src scripts tests recipes .storybook ... --max-warnings=0`
통과, app·test·node 타입 검사 통과
- vitest: tests/unit + tests/component 209 files 2725 tests,
tests/features 등 25 files 141 tests 통과
- `check-registries.ts` PASS, `check-ci-contract.ts` PASS,
`verify-documentation-readiness.ts` PASS_SCOPED
Refs: docs/reviews/2026-09-29-maturity-review/08-presentation.md 08-02, 4.3
731 lines
25 KiB
TypeScript
731 lines
25 KiB
TypeScript
// @vitest-environment jsdom
|
|
|
|
import {
|
|
QueryClient,
|
|
QueryClientProvider,
|
|
} from "@tanstack/react-query";
|
|
import { render, 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 { AuthSessionPort } from "../../../src/application/ports/auth-session-port.ts";
|
|
import type { MutationIntentFactory } from "../../../src/application/ports/mutation-intent-factory.ts";
|
|
import type {
|
|
ReferenceFeatureInput,
|
|
ReferenceResult,
|
|
} from "../../../src/features/reference-feature/application/reference-feature-api.ts";
|
|
import {
|
|
REFERENCE_FEATURE_ID,
|
|
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 type { QueryInvalidationCoordinator } from "../../../src/contracts/query-invalidation.ts";
|
|
import { QueryInvalidationProvider } from "../../../src/presentation/adapters/query/query-invalidation-provider.tsx";
|
|
import { MutationIntentProvider } from "../../../src/presentation/adapters/query/mutation-intent-provider.tsx";
|
|
import { ServerStateScopeProvider } from "../../../src/presentation/adapters/query/server-state-scope-provider.tsx";
|
|
import { createServerStateScopeRuntime } from "../../../src/adapters/query-cache/server-state-scope-runtime.ts";
|
|
import { ApplicationProvider } from "../../../src/presentation/providers/application-provider.tsx";
|
|
import { PreferenceProviders } from "../../../src/presentation/providers/preference-providers.tsx";
|
|
import { AppRouter } from "../../../src/presentation/routes/app-router.tsx";
|
|
import { KO_MESSAGES } from "../../../src/presentation/i18n/catalog.ts";
|
|
import { createTestApplication } from "../../helpers/create-test-application.ts";
|
|
|
|
function renderReference(
|
|
input: ReferenceFeatureInput,
|
|
url = "/examples/reference-resources?limit=5",
|
|
session: AuthSessionPort = createDemoSessionAdapter("authenticated"),
|
|
) {
|
|
window.history.pushState({}, "", url);
|
|
const client = new QueryClient({
|
|
defaultOptions: {
|
|
queries: { retry: false, gcTime: Infinity },
|
|
mutations: { retry: false },
|
|
},
|
|
});
|
|
const invalidation: QueryInvalidationCoordinator = Object.freeze({
|
|
async invalidate() {},
|
|
beginMutation() {
|
|
return Object.freeze({
|
|
async release() {},
|
|
});
|
|
},
|
|
async resetLocal() {},
|
|
dispose() {},
|
|
});
|
|
const serverStateScope = createServerStateScopeRuntime({
|
|
session,
|
|
queryInvalidation: invalidation,
|
|
});
|
|
let intentSequence = 0;
|
|
const mutationIntentFactory: MutationIntentFactory = Object.freeze({
|
|
create(input) {
|
|
intentSequence += 1;
|
|
return Object.freeze({
|
|
intentId: `reference-page-intent-${intentSequence}`,
|
|
operationId: input.operationId,
|
|
canonicalInputIdentity: input.canonicalInputIdentity,
|
|
...(input.requiresIdempotencyKey
|
|
? { idempotencyKey: `reference-page-key-${intentSequence}` }
|
|
: {}),
|
|
createdAtMonotonicMs: intentSequence,
|
|
});
|
|
},
|
|
});
|
|
return Object.assign(render(
|
|
<MutationIntentProvider factory={mutationIntentFactory}>
|
|
<QueryClientProvider client={client}>
|
|
<ServerStateScopeProvider runtime={serverStateScope}>
|
|
<QueryInvalidationProvider coordinator={invalidation}>
|
|
<ApplicationProvider
|
|
application={createTestApplication({
|
|
session,
|
|
featureInputs: { [REFERENCE_FEATURE_ID]: input },
|
|
})}
|
|
>
|
|
<PreferenceProviders>
|
|
<AppRouter />
|
|
</PreferenceProviders>
|
|
</ApplicationProvider>
|
|
</QueryInvalidationProvider>
|
|
</ServerStateScopeProvider>
|
|
</QueryClientProvider>
|
|
</MutationIntentProvider>,
|
|
), { client });
|
|
}
|
|
|
|
function inputWith(
|
|
overrides: Partial<ReferenceFeatureInput> = {},
|
|
): ReferenceFeatureInput {
|
|
return {
|
|
listResources: async () => ({ ok: true, value: [] }),
|
|
createResource: async ({ name }) => ({
|
|
ok: true,
|
|
value: {
|
|
resourceId: "created",
|
|
title: name,
|
|
createdAt: null,
|
|
},
|
|
}),
|
|
getResource: async (resourceId) => ({
|
|
ok: true,
|
|
value: {
|
|
resourceId,
|
|
title: "Detail",
|
|
createdAt: null,
|
|
},
|
|
}),
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* 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());
|
|
expect(screen.getByRole("button", { name: "저장 중…" })).toBeDisabled();
|
|
|
|
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();
|
|
expect(
|
|
screen.getByRole("link", { name: "목록을 새로 불러와 확인" }),
|
|
).toHaveAttribute("href", "/examples/reference-resources");
|
|
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));
|
|
}
|
|
},
|
|
);
|
|
|
|
// 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);
|
|
});
|
|
});
|