From 92082c305c6bd3bc2cc14f4ba0db67f5e1b20487 Mon Sep 17 00:00:00 2001 From: le king fu Date: Fri, 23 Oct 2026 21:00:07 -0400 Subject: [PATCH] test: share find and holding in src/test/elementTree.ts (#467) find(node, pred) returns every element the predicate keeps, depth first, through arrays and fragments; holding(node, type) returns every element one of whose direct children is of the type (the button that holds a Trash2, not the icon). Both keep the semantics of the copies they replace, each proved by elementTree.test.ts. ProfileFormModal.delete.test.ts and BudgetPage.wiring.test.ts drop their local copy and import the helper. Co-Authored-By: Claude Opus 5.5 --- .../profile/ProfileFormModal.delete.test.ts | 16 +-- src/pages/BudgetPage.wiring.test.ts | 12 +- src/test/elementTree.test.ts | 128 ++++++++++++++++++ src/test/elementTree.ts | 54 ++++++++ 4 files changed, 187 insertions(+), 23 deletions(-) create mode 100644 src/test/elementTree.test.ts create mode 100644 src/test/elementTree.ts diff --git a/src/components/profile/ProfileFormModal.delete.test.ts b/src/components/profile/ProfileFormModal.delete.test.ts index 0a281ac..d286ea5 100644 --- a/src/components/profile/ProfileFormModal.delete.test.ts +++ b/src/components/profile/ProfileFormModal.delete.test.ts @@ -6,7 +6,6 @@ // clicks the delete button of the secondary profile through its props, the confirmation // answered by a mocked `confirmAction`. import { describe, it, expect, vi, beforeEach } from "vitest"; -import { isValidElement, type ReactElement, type ReactNode } from "react"; vi.mock("react", async (orig) => (await import("../../test/hookHarness")).fakeReact(await orig())); vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock()); @@ -34,26 +33,17 @@ vi.mock("../../contexts/ProfileContext", () => ({ import { Trash2 } from "lucide-react"; import { hookHarness } from "../../test/hookHarness"; +import { holding, type TreeProps } from "../../test/elementTree"; import ProfileFormModal from "./ProfileFormModal"; const harness = hookHarness(); -type Props = Record & { children?: ReactNode; onClick?: () => Promise }; - -/** The elements of the tree whose children hold an element of the given type. */ -function holding(node: ReactNode, type: unknown): ReactElement[] { - if (Array.isArray(node)) return node.flatMap((n) => holding(n, type)); - if (!isValidElement(node)) return []; - const el = node as ReactElement; - const children = ([] as ReactNode[]).concat(el.props.children ?? []); - const holds = children.some((c) => isValidElement(c) && c.type === type); - return [...(holds ? [el] : []), ...holding(el.props.children, type)]; -} +type Props = TreeProps & { onClick?: () => Promise }; /** Clicks the only delete button, the secondary profile's, and waits for its handler. */ async function clickDelete() { const tree = harness.render(() => ProfileFormModal({ onClose: vi.fn() })); - const buttons = holding(tree, Trash2); + const buttons = holding(tree, Trash2); expect(buttons).toHaveLength(1); await buttons[0].props.onClick?.(); } diff --git a/src/pages/BudgetPage.wiring.test.ts b/src/pages/BudgetPage.wiring.test.ts index fa61036..f8cc83e 100644 --- a/src/pages/BudgetPage.wiring.test.ts +++ b/src/pages/BudgetPage.wiring.test.ts @@ -7,7 +7,7 @@ // identity as React's do. The test plays the grid by calling the callback the // page hands it, then reads what the page hands the card and the grid. import { describe, it, expect, vi, beforeEach } from "vitest"; -import { isValidElement, type ReactElement, type ReactNode } from "react"; +import type { ReactNode } from "react"; vi.mock("react", async (orig) => (await import("../test/hookHarness")).fakeReact(await orig())); const ctx = vi.hoisted(() => ({ @@ -32,6 +32,7 @@ vi.mock("../hooks/useBudget", async (importOriginal) => ({ })); import { hookHarness } from "../test/hookHarness"; +import { find, type TreeElement as AnyElement } from "../test/elementTree"; import BudgetPage from "./BudgetPage"; import BudgetTable from "../components/budget/BudgetTable"; import OnboardingStepCard from "../components/onboarding/OnboardingStepCard"; @@ -43,15 +44,6 @@ import type { BudgetOnboardingTargetKind, OnboardingCounters } from "../shared/t const harness = hookHarness(); -type AnyElement = ReactElement & { children?: ReactNode }>; - -function find(node: ReactNode, pred: (el: AnyElement) => boolean): AnyElement[] { - if (Array.isArray(node)) return node.flatMap((n) => find(n, pred)); - if (!isValidElement(node)) return []; - const el = node as AnyElement; - return [...(pred(el) ? [el] : []), ...find(el.props.children, pred)]; -} - /** Steps 2 to 5 done: the next step is the budget. */ const BUDGET_LEFT: OnboardingCounters = { sources: 1, diff --git a/src/test/elementTree.test.ts b/src/test/elementTree.test.ts new file mode 100644 index 0000000..328ede1 --- /dev/null +++ b/src/test/elementTree.test.ts @@ -0,0 +1,128 @@ +// elementTree — each semantic of the two helpers proved by its own test (#467). +// +// The tests that search a rendered tree can only be as true as these helpers. +// The trees are built here with the real React (`createElement`), in the shapes +// JSX gives them: several children in an array, a `.map` as one child, nested +// arrays, fragments, texts and holes. +import { describe, it, expect, vi } from "vitest"; +import { createElement as h, Fragment, type ReactNode } from "react"; +import { Pencil, Trash2 } from "lucide-react"; +import { find, holding, type TreeElement } from "./elementTree"; + +/** The `id` prop of each element, in the order the helper returns them. */ +const ids = (elements: TreeElement[]) => elements.map((el) => el.props.id); + +const all = () => true; + +describe("elementTree — find", () => { + const tree = h( + "section", + { id: "s" }, + h("div", { id: "a" }, h("span", { id: "a1" }), h("span", { id: "a2" })), + h("div", { id: "b" }, h("div", { id: "b1" })), + ); + + it("returns every element the predicate keeps, depth first: an element before what it holds", () => { + expect(ids(find(tree, all))).toEqual(["s", "a", "a1", "a2", "b", "b1"]); + expect(ids(find(tree, (el) => el.type === "span"))).toEqual(["a1", "a2"]); + }); + + it("keeps an element and what it holds when both match", () => { + expect(ids(find(tree, (el) => el.type === "div"))).toEqual(["a", "b", "b1"]); + }); + + it("reads arrays at any depth: a .map as one child, a list beside a sibling, a nested array, a top-level array", () => { + const rows = [1, 2].map((n) => h("li", { key: n, id: `li${n}` })); + const list = h("ul", { key: "ul", id: "ul" }, h("li", { id: "first" }), rows); + const node: ReactNode = [list, [[h("p", { key: "p", id: "p" })]]]; + expect(ids(find(node, (el) => el.type === "li"))).toEqual(["first", "li1", "li2"]); + expect(ids(find(node, (el) => el.type === "p"))).toEqual(["p"]); + expect(ids(find(h("ol", { id: "ol" }, rows), (el) => el.type === "li"))).toEqual(["li1", "li2"]); + }); + + it("treats a fragment as an element: the predicate sees it, then its children", () => { + const node = h("div", { id: "d" }, h(Fragment, null, h("i", { id: "i1" }), h("i", { id: "i2" }))); + expect(ids(find(node, (el) => el.type === "i"))).toEqual(["i1", "i2"]); + const fragments = find(node, (el) => el.type === Fragment); + expect(fragments).toHaveLength(1); + expect(fragments[0].type).toBe(Fragment); + }); + + it("skips texts, numbers and holes", () => { + const node = h("p", { id: "p" }, "text", 0, null, undefined, false, true, h("b", { id: "b" })); + expect(ids(find(node, all))).toEqual(["p", "b"]); + expect(find("text", all)).toEqual([]); + expect(find(null, all)).toEqual([]); + }); + + it("reads props.children only: an element passed in another prop is not reached", () => { + const node = h("button", { id: "button", icon: h(Trash2) }, "label"); + expect(find(node, (el) => el.type === Trash2)).toEqual([]); + expect(ids(find(node, all))).toEqual(["button"]); + }); + + it("never calls a component of the tree: what it renders is not there", () => { + const Child = vi.fn(() => h("b", { id: "inside" })); + const node = h("div", { id: "d" }, h(Child, { id: "child" })); + expect(find(node, (el) => el.type === "b")).toEqual([]); + expect(ids(find(node, (el) => el.type === Child))).toEqual(["child"]); + expect(Child).not.toHaveBeenCalled(); + }); +}); + +describe("elementTree — holding", () => { + it("returns the element whose child is of the type: the button, neither the icon nor the row around it", () => { + const row = h( + "div", + { id: "row" }, + h("span", { id: "label" }, "Loyer"), + h("button", { id: "edit" }, h(Pencil)), + h("button", { id: "delete" }, h(Trash2), "Supprimer"), + ); + expect(ids(holding(row, Trash2))).toEqual(["delete"]); + expect(ids(holding(row, Pencil))).toEqual(["edit"]); + }); + + it("returns every holder, depth first, a holder before a holder it holds", () => { + const rows = [1, 2, 3].map((n) => + h("tr", { key: n, id: `row${n}` }, h("td", { id: `cell${n}` }, h("button", { id: `delete${n}` }, h(Trash2)))), + ); + expect(ids(holding(h("tbody", { id: "body" }, rows), Trash2))).toEqual(["delete1", "delete2", "delete3"]); + const nested = h("div", { id: "outer" }, h(Trash2), h("div", { id: "inner" }, h(Trash2))); + expect(ids(holding(nested, Trash2))).toEqual(["outer", "inner"]); + }); + + it("returns a holder once, however many children of the type it holds", () => { + const button = h("button", { id: "b" }, h(Trash2, { key: 1 }), h(Trash2, { key: 2 })); + expect(ids(holding(button, Trash2))).toEqual(["b"]); + }); + + it("compares the type by identity: a tag name, a component", () => { + const Child = () => null; + const Other = () => null; + const node = h("td", { id: "cell" }, h("button", { id: "button" }), h("div", { id: "div" }, h(Child))); + expect(ids(holding(node, "button"))).toEqual(["cell"]); + expect(ids(holding(node, Child))).toEqual(["div"]); + expect(holding(node, Other)).toEqual([]); + }); + + it("reads props.children one level deep: a list alone is direct, a list beside a sibling is not", () => { + const alone = h("td", { id: "alone" }, [h(Trash2, { key: 1 })]); + const beside = h("td", { id: "beside" }, "label", [h(Trash2, { key: 1 })]); + expect(ids(holding(alone, Trash2))).toEqual(["alone"]); + expect(holding(beside, Trash2)).toEqual([]); + }); + + it("lets a fragment hold its own children, not its parent", () => { + const node = h("div", { id: "d" }, h(Fragment, null, h(Trash2))); + const holders = holding(node, Trash2); + expect(holders).toHaveLength(1); + expect(holders[0].type).toBe(Fragment); + }); + + it("reads props.children only, and skips texts and holes", () => { + expect(holding(h("button", { id: "b", icon: h(Trash2) }, "label"), Trash2)).toEqual([]); + expect(holding(h("p", { id: "p" }, "text", null, false), Trash2)).toEqual([]); + expect(holding(null, Trash2)).toEqual([]); + }); +}); diff --git a/src/test/elementTree.ts b/src/test/elementTree.ts new file mode 100644 index 0000000..6a517ba --- /dev/null +++ b/src/test/elementTree.ts @@ -0,0 +1,54 @@ +// elementTree — searching the tree a component returns, for tests without jsdom (#467). +// +// A test that calls a component as a plain function, under the shared hook +// harness of this folder or without it, gets back a tree of React elements, +// not a DOM. These two helpers search that tree; before #467, test files kept +// their own copy. Each semantic below is proved by elementTree.test.ts. +// +// - `find(node, pred)`: every element of the tree for which `pred` is true, +// depth first: an element before what it holds, siblings in order, and an +// element kept with what it holds when both match. Arrays (several children, +// the result of a `.map`) are read at any depth, and a fragment is an element +// like any other: `pred` sees it, then its children. The elements of one +// type: `find(tree, (el) => el.type === CategoryForm)`. +// - `holding(node, type)`: every element one of whose direct children is an +// element of `type`, in the same order and once each: the button that holds +// a `Trash2`, neither the icon nor the row around the button. A direct child +// is an item of `props.children`, an array there being read one level deep: +// in `{rows}` the items of `rows` are direct children of the cell, +// in `{label}{rows}` they are not. A fragment holds its own +// children, not its parent. +// +// Both read `props.children` only: an element passed in another prop +// (`icon={}`) is not reached. A component in the tree is an element, +// never called, as under the harness: what a child component renders is not +// in the tree, and the test reaches it through the props of the child's +// element (`find(tree, (el) => el.type === CategoryForm)[0].props.onDelete()`). +import { isValidElement, type ReactElement, type ReactNode } from "react"; + +/** The props of an element of the tree: any props, and its children. */ +export type TreeProps = Record & { children?: ReactNode }; + +/** An element of the tree; `P` narrows its props for a test that knows them. */ +export type TreeElement

= ReactElement

; + +/** Every element of `node` for which `pred` is true, depth first, through arrays and fragments. */ +export function find

( + node: ReactNode, + pred: (el: TreeElement

) => boolean, +): TreeElement

[] { + if (Array.isArray(node)) return node.flatMap((n) => find(n, pred)); + if (!isValidElement(node)) return []; + const el = node as TreeElement

; + return [...(pred(el) ? [el] : []), ...find(el.props.children, pred)]; +} + +/** Every element of `node` one of whose direct children is an element of `type`, depth first. */ +export function holding

(node: ReactNode, type: unknown): TreeElement

[] { + if (Array.isArray(node)) return node.flatMap((n) => holding

(n, type)); + if (!isValidElement(node)) return []; + const el = node as TreeElement

; + const children = ([] as ReactNode[]).concat(el.props.children ?? []); + const holds = children.some((c) => isValidElement(c) && c.type === type); + return [...(holds ? [el] : []), ...holding

(el.props.children, type)]; +}