Files
clean-architecture-frontend…/tests/features/reference-feature/reference-production-vertical.test.tsx
T
DongHyeonka 498ae87554 test(evidence): HTTP 시나리오와 타입 음성 fixture를 테스트 계약으로 옮긴다 (0929/10-02)
문제: 샘플 제거 절차(scripts/test-sample-removal.ts)의 SAMPLE_EXTRAS가
플랫폼 검사도 함께 지운다. HTTP 실패 시나리오 카탈로그(57개)와 tests/mocks,
test:http-scenario-evidence(FE-GATE-007), 기능 API 타입 음성 fixture 8개와
check:types:fixture:* 8개(FE-GATE-003)가 참조 기능 계약을 import해서
샘플 소유로 묶여 있었다. 드릴은 플랫폼 경로 4개만 확인하므로 통과하고,
제품은 가드레일이 줄었다는 것을 모른다.

방법: 카탈로그와 handler를 tests/helpers/external-contract-fixture.ts의
테스트 계약(TEST_LIST/DETAIL, 명령)으로 옮겼다. 바이트 상한·명령 여부·성공
status는 계약에서 읽는다. 명령은 효과를 분류하는 패키지처럼
TEST_CLASSIFIED_CREATE_HTTP_CONTRACT를 더해 기존 기대값(401/403/429·422·
409 CONFLICT는 NOT_APPLIED, 409 IN_FLIGHT·404·503은 MAYBE_APPLIED)을
그대로 지킨다. TEST_CREATE_HTTP_CONTRACT의 분류기는 실행기 테스트가
"분류기 없음"을 확인하는 데 쓰므로 바꾸지 않았다. 문제 스키마에 선택
code만 더했다.
타입 fixture는 fixture tsconfig만 컴파일하는 fixture-feature-contract.ts의
테스트 기능(operation ID를 literal로 좁힌 테스트 계약, "fixture-feature"
입력 등록)을 쓴다. 등록 augmentation이 app·test 프로그램에 들어가지 않는다.
참조 기능 전용 handler(성공 응답만 쓰였다)는 tests/features/reference-feature
로 옮겼다. test-evidence.json의 owner는 platform이다. SAMPLE_EXTRAS에서
이 경로·스크립트를 빼고, 드릴의 플랫폼 보존 확인 목록에 16개 경로를 더했다.
샘플이 증거 정책을 갖지 않으므로 "등록 안 됨" 오류 검사는 지웠다.
버린 대안: README에 "함께 사라지는 검사" 목록만 적는다. 비용은 0이지만
검사는 계속 사라진다.

위험: fixture 스크립트 이름(check:types:fixture:reference-operation)과
파일 이름은 그대로라 이름이 내용(TEST_GET_ENTITY)과 다르다. CI 스크립트·
gates·워크플로 스냅샷을 함께 바꿔야 해서 미뤘다. 드릴의 제외 목록에 있는
tests/unit/http-scenario-evidence.test.ts는 그대로 뒀다.
test:sample-removal 자체는 pnpm이 필요해 돌리지 않았다.

검증: RED는 기준 복사본에 드릴의 삭제 목록을 적용했다. 카탈로그 테스트·
tests/mocks·타입 fixture 16파일이 지워지고 CI 스크립트 9개가 빠지는데 보존
확인은 4/4로 통과한다. GREEN은 같은 적용 뒤 보존 확인 16/16, 잔여 이름은
드릴이 빼는 removal-fixture.test.ts 하나, 타입 fixture 8개가 기존과 같은
진단(TS2345·2741·2353·2322·2345·2322·2322·2339) 1건씩으로 실패, 카탈로그
57/57 실행·check-test-evidence --scenario-only PASS, tests/component와
카탈로그 36파일 226개 통과, tsc -p tsconfig.test.json 통과. worktree에서는
테스트 계약 사용 파일·참조 기능·카탈로그 59파일 535개, scale session 2파일
통과, 음성 fixture의 양성 대조 컴파일 통과, tsc test·node 통과,
check-ci-contract PASS, 바꾼 파일 eslint 통과.
2026-11-03 01:18:36 +09:00

381 lines
14 KiB
TypeScript

// @vitest-environment jsdom
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { http, HttpResponse } from "msw";
import {
afterAll,
afterEach,
beforeAll,
describe,
expect,
it,
vi,
} from "vitest";
import { createRuntimeComposition } from "../../../src/bootstrap/create-runtime-composition.ts";
import { RuntimeApplication } from "../../../src/bootstrap/runtime-application.tsx";
import { createBootstrapHandlers } from "../../mocks/handlers/bootstrap.ts";
import { createReferenceResourceHandlers } from "./reference-resource-handlers.ts";
import { createStrictMockServer } from "../../mocks/server.ts";
const runtimeConfig = {
APP_ENV: "local",
API_BASE_URL: "https://api.test",
REQUEST_TIMEOUT_MS: 10_000,
MAX_RETRY_ATTEMPTS: 0,
TELEMETRY_ENABLED: false,
AUTH_MODE: "demo",
CONFIG_SCHEMA_VERSION: "1",
API_CONTRACT_VERSION: "1",
RELEASE_MANIFEST_URL: "/release-manifest.json",
BUILD_ID: "local-build",
RELEASE_ID: "local-release",
};
const releaseManifest = {
schemaVersion: 1,
appVersion: "0.2.0",
buildId: "local-build",
commitSha: "local",
configSchemaVersion: "1",
apiContractVersion: "1",
assetManifestHash: "test-hash",
releaseId: "local-release",
builtAt: "2026-07-26T00:00:00.000Z",
routeChunks: {
"route-home": "assets/home.js",
"route-examples-ui": "assets/ui.js",
"route-examples-states": "assets/states.js",
"route-examples-auth": "assets/auth.js",
"route-reference-resources": "assets/reference.js",
"route-reference-resource-detail": "assets/reference-detail.js",
"route-reference-resource-form": "assets/reference-form.js",
"route-reference-resource-status": "assets/reference-status.js",
"route-not-found": "assets/not-found.js",
},
};
const listRequests = vi.fn();
const createRequests = vi.fn();
const resources = [{ id: "reference-1", name: "Existing" }];
const mockApi = createStrictMockServer(
...createBootstrapHandlers(runtimeConfig, releaseManifest),
...createReferenceResourceHandlers({
resources,
onList: listRequests,
onCreate: createRequests,
}),
);
beforeAll(mockApi.listen);
afterEach(() => {
mockApi.reset();
listRequests.mockClear();
createRequests.mockClear();
resources.splice(1);
});
afterAll(mockApi.close);
const absoluteFetch: typeof fetch = (input, init) => {
if (input instanceof Request) return fetch(input, init);
const url = new URL(
input instanceof URL ? input.href : input,
"http://app.test",
);
return fetch(url, init);
};
describe("reference feature production vertical path", () => {
it("traverses bootstrap, router, application, HTTP schema/mapper and query cache", async () => {
const user = userEvent.setup();
const composition = await createRuntimeComposition({
fetcher: absoluteFetch,
host: {},
});
window.history.pushState(
{},
"",
"/examples/reference-resources?tags=open&tags=new&limit=5",
);
render(<RuntimeApplication composition={composition} />);
await user.click(
await screen.findByRole("button", { name: "로그인 시작" }),
);
expect(await screen.findByText("Existing")).toBeVisible();
expect(listRequests).toHaveBeenCalledWith(
"?limit=5&tags=open&tags=new",
);
await user.click(screen.getByRole("button", { name: "새 항목 만들기" }));
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
" Created ",
);
await user.click(screen.getByRole("button", { name: "저장" }));
expect(await screen.findByText("저장했습니다.")).toBeVisible();
await user.click(screen.getByRole("button", { name: "목록으로 돌아가기" }));
expect(await screen.findByText("Created")).toBeVisible();
expect(createRequests).toHaveBeenCalledWith({ name: "Created" });
expect(listRequests.mock.calls.length).toBeGreaterThanOrEqual(2);
});
it("resends a create whose 504 lost the response with the same Idempotency-Key", async () => {
const user = userEvent.setup();
const idempotencyKeys: (string | null)[] = [];
mockApi.server.use(
http.post("https://api.test/api/reference-resources", async ({ request }) => {
idempotencyKeys.push(request.headers.get("idempotency-key"));
// The first request reaches the server; only its response is lost.
if (idempotencyKeys.length === 1) {
return new HttpResponse(null, { status: 504 });
}
const body = (await request.json()) as { name: string };
return HttpResponse.json(
{
id: "reference-created",
name: body.name,
createdAt: "2026-07-26T00:00:00.000Z",
},
{ status: 201 },
);
}),
);
const composition = await createRuntimeComposition({
fetcher: absoluteFetch,
host: {},
});
window.history.pushState({}, "", "/examples/reference-resources/new");
render(<RuntimeApplication composition={composition} />);
await user.click(
await screen.findByRole("button", { name: "로그인 시작" }),
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"Lost response",
);
await user.click(screen.getByRole("button", { name: "저장" }));
await user.click(
await screen.findByRole("button", { name: "같은 요청으로 다시 보내기" }),
);
expect(await screen.findByText("저장했습니다.")).toBeVisible();
expect(idempotencyKeys).toHaveLength(2);
expect(idempotencyKeys[0]).toMatch(/^[\x21-\x7e]+$/u);
expect(idempotencyKeys[1]).toBe(idempotencyKeys[0]);
});
// 0929/03-04. A write past its deadline has no server answer to echo an
// id, so the screen shows the id the request itself carried.
it("shows the sent x-correlation-id for a create past its deadline", async () => {
const user = userEvent.setup();
const sentIds: (string | null)[] = [];
mockApi.server.use(
http.get("http://app.test/config.json", () =>
HttpResponse.json({ ...runtimeConfig, REQUEST_TIMEOUT_MS: 200 }),
),
http.post("https://api.test/api/reference-resources", async ({ request }) => {
sentIds.push(request.headers.get("x-correlation-id"));
// The server is still working when the client deadline ends.
await new Promise<void>((resolve) => {
request.signal.addEventListener("abort", () => resolve(), { once: true });
});
return new HttpResponse(null, { status: 504 });
}),
);
const composition = await createRuntimeComposition({
fetcher: absoluteFetch,
host: {},
});
window.history.pushState({}, "", "/examples/reference-resources/new");
render(<RuntimeApplication composition={composition} />);
await user.click(
await screen.findByRole("button", { name: "로그인 시작" }),
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"Past the deadline",
);
await user.click(screen.getByRole("button", { name: "저장" }));
expect(
await screen.findByText("변경 결과를 확인할 수 없습니다."),
).toBeVisible();
expect(sentIds).toHaveLength(1);
expect(sentIds[0]).toMatch(/^[A-Za-z0-9._:-]{1,128}$/u);
expect(screen.getByText(`지원 참조: ${sentIds[0]}`)).toBeVisible();
});
it("keeps the key when the resend meets the first attempt still in flight (0929/03-01)", async () => {
const user = userEvent.setup();
const idempotencyKeys: (string | null)[] = [];
// A server that deduplicates by key: one receipt per created resource.
const receipts = new Map<string, Record<string, string>>();
let firstAttemptRunning = true;
mockApi.server.use(
http.post("https://api.test/api/reference-resources", async ({ request }) => {
const key = request.headers.get("idempotency-key") ?? "";
idempotencyKeys.push(key);
const receipt = receipts.get(key);
if (receipt) {
if (firstAttemptRunning) {
// The paired backend answers a same-key request while the first
// attempt still runs with 409 IDEMPOTENT_IN_FLIGHT.
firstAttemptRunning = false;
return HttpResponse.json(
{
type: "https://api.test/problems/idempotent_in_flight",
title: "IDEMPOTENT_IN_FLIGHT",
status: 409,
code: "IDEMPOTENT_IN_FLIGHT",
},
{
status: 409,
headers: { "content-type": "application/problem+json" },
},
);
}
return HttpResponse.json(receipt, { status: 201 });
}
const body = (await request.json()) as { name: string };
const resource = {
id: `reference-created-${receipts.size + 1}`,
name: body.name,
createdAt: "2026-07-26T00:00:00.000Z",
};
receipts.set(key, resource);
// The first attempt reaches the server; only its response is lost.
if (receipts.size === 1) return new HttpResponse(null, { status: 504 });
return HttpResponse.json(resource, { status: 201 });
}),
);
const composition = await createRuntimeComposition({
fetcher: absoluteFetch,
host: {},
});
window.history.pushState({}, "", "/examples/reference-resources/new");
render(<RuntimeApplication composition={composition} />);
await user.click(
await screen.findByRole("button", { name: "로그인 시작" }),
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"Slow write",
);
await user.click(screen.getByRole("button", { name: "저장" }));
await user.click(
await screen.findByRole("button", { name: "같은 요청으로 다시 보내기" }),
);
await waitFor(() => expect(idempotencyKeys).toHaveLength(2));
// After the 409 the user takes the next step the screen offers.
const next = await waitFor(() => {
const resend = screen.queryByRole("button", {
name: "같은 요청으로 다시 보내기",
});
if (resend) return resend;
const save = screen.getByRole("button", { name: "저장" });
expect(save).toBeEnabled();
return save;
});
const shownAfterInFlight = {
unknown: screen.queryByText("변경 결과를 확인할 수 없습니다.") !== null,
conflict: screen.queryAllByText(/충돌/).length > 0,
};
await user.click(next);
await waitFor(() => expect(idempotencyKeys).toHaveLength(3));
const [first] = idempotencyKeys;
expect(idempotencyKeys).toEqual([first, first, first]);
expect(receipts.size).toBe(1);
expect(shownAfterInFlight).toEqual({ unknown: true, conflict: false });
expect(await screen.findByText("저장했습니다.")).toBeVisible();
});
it.each([
// The demo session treats a server 401 as signed out; the route guard
// then asks for sign-in and the form is gone.
[401, "세션이 필요합니다."],
[403, "이 작업을 수행할 권한이 없습니다."],
[429, "요청이 많습니다. 잠시 후 다시 시도해 주세요."],
])(
"treats a create rejected with %i as not applied, not unknown",
async (status, guidance) => {
const user = userEvent.setup();
mockApi.server.use(
http.post(
"https://api.test/api/reference-resources",
() => new HttpResponse(null, { status }),
),
);
const composition = await createRuntimeComposition({
fetcher: absoluteFetch,
host: {},
});
window.history.pushState({}, "", "/examples/reference-resources/new");
render(<RuntimeApplication composition={composition} />);
await user.click(
await screen.findByRole("button", { name: "로그인 시작" }),
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"Rejected",
);
await user.click(screen.getByRole("button", { name: "저장" }));
expect(await screen.findByText(guidance)).toBeVisible();
expect(
screen.queryByText("변경 결과를 확인할 수 없습니다."),
).not.toBeInTheDocument();
expect(
screen.queryByRole("button", { name: "같은 요청으로 다시 보내기" }),
).not.toBeInTheDocument();
expect(document.body).not.toHaveTextContent("입력 내용을 확인해 주세요.");
},
);
it("shows a server 422 field error on its field (03-04)", async () => {
const user = userEvent.setup();
mockApi.server.use(
http.post("https://api.test/api/reference-resources", () =>
HttpResponse.json(
{
type: "https://api.test/problems/validation_rejected",
title: "VALIDATION_REJECTED",
status: 422,
code: "VALIDATION_REJECTED",
issues: [
{ path: "name", code: "too_big", message: "backend copy" },
{ path: "serverOnly", code: "REQUIRED" },
],
},
{ status: 422 },
),
),
);
const composition = await createRuntimeComposition({
fetcher: absoluteFetch,
host: {},
});
window.history.pushState({}, "", "/examples/reference-resources/new");
render(<RuntimeApplication composition={composition} />);
await user.click(
await screen.findByRole("button", { name: "로그인 시작" }),
);
const name = await screen.findByRole("textbox", { name: /새 항목 이름/ });
await user.type(name, "Too long for the server");
await user.click(screen.getByRole("button", { name: "저장" }));
const summary = await screen.findByRole("alert");
expect(summary).toHaveTextContent("새 항목 이름: 입력값이 너무 깁니다.");
expect(summary).toHaveTextContent("서버가 확인하지 못한 입력 항목이 있습니다.");
expect(name).toHaveAttribute("aria-invalid", "true");
expect(document.body).not.toHaveTextContent("backend copy");
});
});