Files
clean-architecture-frontend…/tests/fixtures/manual-code-blocks/manual-code-blocks.check.tsx
DongHyeonka 01cac930e0 docs(manual): 샘플 대신 생성 기능 경로와 시험하는 코드 조각을 예제로 둔다
매뉴얼 예제 칸 14곳(S4 3.3절)과 산문 30여 곳이 참조 기능을
가리킨다. problem details(Envelope가 아닌 백엔드) 응답 매핑의 예는
참조 기능에만 있다.

생성기 출력이 그 모양을 만들면 그 경로로 바꿨다. 없으면 매뉴얼 안
코드 조각으로 썼다: problem details의 분류와 매핑(02 결정표 4절,
소유자 결정 D1), 도메인 모델, 검색값 스키마와 hook, 실패 행동 hook,
403 페이지 시험. 조각마다 manual-code-block 표식에 둘 경로를 적는다.
tests/unit/manual-code-blocks.test.ts가 저장소 사본에 create:feature
invoice-feature --with-create를 만들고 조각을 그 경로에 그대로 넣어
tsc(app, test), eslint, check:architecture, 그 기능 폴더의 vitest를
돈다. 조각의 동작은 tests/fixtures/manual-code-blocks/가 본다.

위험: 403 조각은 본문 없는 403으로 답한다. 공유 시나리오
forbidden-403(JSON 본문)은 jsdom + MSW에서 실행기의 본문 cancel이
끝나지 않아 화면이 로딩에 머물렀다. 실행기는 고치지 않았다. 사본에
이미 invoice-feature가 있는 프로젝트에서는 이 시험이 생성 단계에서
실패한다.

검증(desktop): test:unit 213 files 3096 passed(이 커밋까지),
verify:documentation PASS_SCOPED, lint 통과.
2026-11-08 13:51:55 +09:00

193 lines
8.2 KiB
TypeScript

// @vitest-environment jsdom
// What the manual's code blocks do. tests/unit/manual-code-blocks.test.ts
// copies this file into the tests folder of the feature the blocks are
// written for, in a repository copy that has that feature and the blocks at
// their marked paths, and puts the feature's folder name for `{{feature}}`.
// The imports resolve there, not here: written out, they would read as a
// product feature's residue to the removal drill (scripts/lib/feature-residue.ts).
import { act, renderHook } from "@testing-library/react";
import type { ReactNode } from "react";
import { MemoryRouter, useLocation } from "react-router-dom";
import { describe, expect, it, vi } from "vitest";
import { createAnonymousSessionAdapter } from "../../../src/adapters/auth/index.ts";
import { createFailure } from "../../../src/contracts/errors.ts";
import { mapInvoiceCreateProblem } from "../../../src/features/{{feature}}/adapters/invoice-problem-mapping.ts";
import { invoiceListSearchSchema } from "../../../src/features/{{feature}}/contracts/invoice-list-search.ts";
import {
INVOICE_CREATE_EFFECT,
INVOICE_PROBLEM_VALIDATOR,
} from "../../../src/features/{{feature}}/contracts/invoice-problem-details.ts";
import { createInvoice } from "../../../src/features/{{feature}}/domain/invoice.ts";
import { useInvoiceFailureAction } from "../../../src/features/{{feature}}/presentation/use-invoice-failure-action.ts";
import { useInvoiceListFilters } from "../../../src/features/{{feature}}/presentation/use-invoice-list-filters.ts";
import { ApplicationProvider } from "../../../src/presentation/providers/application-provider.tsx";
import { SessionProvider } from "../../../src/presentation/providers/session-provider.tsx";
import { RouteInputProvider } from "../../../src/presentation/routes/route-input.tsx";
import { createTestApplication } from "../../helpers/create-test-application.ts";
const PROBLEM = Object.freeze({
type: "https://problems.example/invoice",
title: "Invoice refused",
});
describe("01 step 2: the domain model", () => {
it("keeps an invoice that falls due on or after its issue day, frozen", () => {
const invoice = createInvoice({ invoiceId: "inv-1", issuedOn: "2026-11-01", dueOn: "2026-11-01" });
expect(invoice).toEqual({ invoiceId: "inv-1", issuedOn: "2026-11-01", dueOn: "2026-11-01" });
expect(Object.isFrozen(invoice)).toBe(true);
});
it("refuses an invoice due before it is issued, and a date that is no calendar date", () => {
expect(() =>
createInvoice({ invoiceId: "inv-1", issuedOn: "2026-11-02", dueOn: "2026-11-01" }),
).toThrow(RangeError);
expect(() =>
createInvoice({ invoiceId: "inv-1", issuedOn: "2026-11-02", dueOn: "next week" }),
).toThrow(RangeError);
});
});
describe("02 section 4: a problem-details backend", () => {
it("reads a problem details body and keeps only its fields", () => {
const read = INVOICE_PROBLEM_VALIDATOR.safeParse({
...PROBLEM,
status: 422,
code: "INVOICE_REJECTED",
detail: "a backend message the screen never shows",
issues: [{ path: "dueOn", code: "BEFORE_ISSUE", message: "dropped" }],
});
expect(read).toEqual({
success: true,
data: {
...PROBLEM,
status: 422,
code: "INVOICE_REJECTED",
issues: [{ path: "dueOn", code: "BEFORE_ISSUE" }],
},
});
expect(INVOICE_PROBLEM_VALIDATOR.safeParse({ type: PROBLEM.type, status: 400 }).success).toBe(false);
expect(INVOICE_PROBLEM_VALIDATOR.schemaId).toBe("InvoiceProblem");
});
it("calls a create refused only for 400, 422 and the declared 409 code", () => {
const classify = (status: number, code?: string) =>
INVOICE_CREATE_EFFECT.classifyProblem({
status,
problem: { ...PROBLEM, status, ...(code === undefined ? {} : { code }) },
});
expect(classify(400)).toBe("NOT_APPLIED");
expect(classify(422, "INVOICE_REJECTED")).toBe("NOT_APPLIED");
expect(classify(409, "CONFLICT")).toBe("NOT_APPLIED");
// A resend that meets the first attempt still running keeps its key.
expect(classify(409, "IDEMPOTENT_IN_FLIGHT")).toBe("MAYBE_APPLIED");
expect(classify(409)).toBe("MAYBE_APPLIED");
expect(classify(503, "IDEMPOTENCY_UNAVAILABLE")).toBe("MAYBE_APPLIED");
expect(classify(500)).toBe("MAYBE_APPLIED");
expect(INVOICE_CREATE_EFFECT.classifyStatus?.(403)).toBe("NOT_APPLIED");
});
it("maps a conflict, a key rule mismatch and field issues, and leaves the rest to the executor", () => {
const problem = (status: number, extra: Readonly<Record<string, unknown>> = {}) => ({
...PROBLEM,
status,
...extra,
});
expect(mapInvoiceCreateProblem(problem(409, { code: "CONFLICT" }), { status: 409 })).toEqual({
kind: "CONFLICT",
code: "CONFLICT",
});
expect(mapInvoiceCreateProblem(problem(409), { status: 409 })).toEqual({
kind: "CONFLICT",
code: "INVOICE_CONFLICT",
});
expect(
mapInvoiceCreateProblem(problem(400, { code: "IDEMPOTENCY_KEY_INVALID" }), { status: 400 }),
).toEqual({ kind: "UNKNOWN_CLIENT_FAILURE", code: "IDEMPOTENCY_KEY_INVALID" });
expect(
mapInvoiceCreateProblem(problem(422, { issues: [{ path: "dueOn", code: "BEFORE_ISSUE" }] }), {
status: 422,
}),
).toEqual({
kind: "VALIDATION_REJECTED",
code: "INVOICE_REJECTED",
validationIssues: [{ path: "dueOn", code: "BEFORE_ISSUE" }],
});
expect(mapInvoiceCreateProblem(problem(400), { status: 400 })).toBeUndefined();
expect(mapInvoiceCreateProblem(problem(503), { status: 503 })).toBeUndefined();
});
});
describe("01 step 6: reading the list route's search values", () => {
const withSearch = (search: Readonly<Record<string, unknown>>) =>
function Search({ children }: Readonly<{ children: ReactNode }>) {
return (
<RouteInputProvider input={{ routeId: "INVOICE_LIST", params: {}, search }}>
{children}
</RouteInputProvider>
);
};
it("reads the search the codec accepted, typed", () => {
expect(renderHook(useInvoiceListFilters, { wrapper: withSearch({ status: "open" }) }).result.current).toEqual({
status: "open",
});
expect(renderHook(useInvoiceListFilters, { wrapper: withSearch({}) }).result.current).toEqual({});
});
it("refuses a value the router must answer with the invalid-route screen", () => {
expect(invoiceListSearchSchema.safeParse({ status: "void" }).success).toBe(false);
expect(invoiceListSearchSchema.safeParse({ status: "open", page: "2" }).success).toBe(false);
});
});
describe("01 step 8: the failure action of a page", () => {
function renderAction(failure: Parameters<typeof useInvoiceFailureAction>[0]) {
const beginSignIn = vi.fn(async (_returnTo?: string) => {});
const application = createTestApplication({
session: { ...createAnonymousSessionAdapter(), beginSignIn },
});
const rendered = renderHook(
() => ({ handle: useInvoiceFailureAction(failure), location: useLocation() }),
{
wrapper: ({ children }: Readonly<{ children: ReactNode }>) => (
<ApplicationProvider application={application}>
<SessionProvider>
<MemoryRouter initialEntries={["/invoice?status=open#total"]}>{children}</MemoryRouter>
</SessionProvider>
</ApplicationProvider>
),
},
);
return { beginSignIn, rendered };
}
it("signs in again and comes back to the same URL", async () => {
const { beginSignIn, rendered } = renderAction(createFailure("AUTH_REQUIRED", "INVOICE_LIST_ITEMS", 0));
await act(async () => rendered.result.current.handle?.());
expect(beginSignIn).toHaveBeenCalledWith("/invoice?status=open#total");
});
it("leaves a forbidden screen for home", async () => {
const { rendered } = renderAction(createFailure("FORBIDDEN", "INVOICE_LIST_ITEMS", 0));
await act(async () => rendered.result.current.handle?.());
expect(rendered.result.current.location.pathname).toBe("/");
});
it("gives no handler for a retry or for no failure: the query owns retry", () => {
expect(
renderAction(createFailure("NETWORK_UNREACHABLE", "INVOICE_LIST_ITEMS", 0)).rendered.result.current.handle,
).toBeUndefined();
expect(renderAction(undefined).rendered.result.current.handle).toBeUndefined();
});
});