// @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> = {}) => ({ ...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>) => function Search({ children }: Readonly<{ children: ReactNode }>) { return ( {children} ); }; 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[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 }>) => ( {children} ), }, ); 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(); }); });