test(confirm): behaviour tests of the four sites the guard alone held (#467) #492

Merged
maximus merged 5 commits from issue-467-confirm-behaviour-tests into main 2026-10-24 18:10:54 +00:00
9 changed files with 737 additions and 24 deletions

View file

@ -661,7 +661,9 @@ Sémantique simulée, chaque point prouvé par `src/test/hookHarness.test.ts` :
Non simulé : le nouveau rendu après un setter ou un dispatch, les enfants (un composant dans l'arbre rendu reste un élément), le DOM, le concurrent, la boucle de mises à jour pendant le rendu (le `render()` suivant la lit), et un reducer qui change d'un rendu à l'autre : le `dispatch` d'un `useReducer` garde le reducer du premier rendu (il est créé une fois, avec l'emplacement), là où React applique celui du dernier rendu. Un reducer défini au niveau du module, seul cas utilisé, n'est pas touché.
Utilisateurs : 21 fichiers de test au 2026-10-20, que `grep -rl "test/hookHarness" src --include='*.test.*'` liste (sans le filtre, la commande nomme aussi le harnais) ; d'abord ceux de #389 (`useOnboardingChecklist.wiring.test.ts`, `UsersSettingsPage.test.tsx`, `BudgetTable.wiring.test.ts`, `BudgetPage.wiring.test.ts`, `AppShell.slot.test.tsx`, `OnboardingStepCard.test.tsx`, `PriceFetchConsentToggle.test.tsx`), puis les tests de câblage et de hooks venus après (`PriceFetchControl.test.tsx` en #437, `TransactionTable.wiring.test.ts`, `useCategories.test.ts`…). `CategoryCombobox.placement.test.ts` y fait passer `useLayoutEffect` pour `useEffect` et `useId` pour une constante, dans ce seul fichier (#429). Hors périmètre de #409, `useImportWizard.mount.test.ts` et `useImportWizard.executeImport.test.ts` gardent leurs faux non persistants ; `useImportWizard.samples.test.ts` (« Créer un dossier d'exemple », #384) passe par le harnais partagé.
Utilisateurs : 25 fichiers de test au 2026-10-23, que `grep -rl "test/hookHarness" src --include='*.test.*'` liste (sans le filtre, la commande nomme aussi le harnais) ; d'abord ceux de #389 (`useOnboardingChecklist.wiring.test.ts`, `UsersSettingsPage.test.tsx`, `BudgetTable.wiring.test.ts`, `BudgetPage.wiring.test.ts`, `AppShell.slot.test.tsx`, `OnboardingStepCard.test.tsx`, `PriceFetchConsentToggle.test.tsx`), puis les tests de câblage et de hooks venus après (`PriceFetchControl.test.tsx` en #437, `TransactionTable.wiring.test.ts`, `useCategories.test.ts`…), dont les quatre tests de suppression de #467 (`CategoryDetailPanel.delete.test.ts`, `AdjustmentDetailPanel.delete.test.ts`, `TemplateActions.delete.test.ts`, `AccountsPage.delete.test.ts`) : ce qu'un gestionnaire fait de la réponse de `confirmAction`, que `native-dialog-guard.test.ts` ne voit pas. `CategoryCombobox.placement.test.ts` y fait passer `useLayoutEffect` pour `useEffect` et `useId` pour une constante, dans ce seul fichier (#429). Hors périmètre de #409, `useImportWizard.mount.test.ts` et `useImportWizard.executeImport.test.ts` gardent leurs faux non persistants ; `useImportWizard.samples.test.ts` (« Créer un dossier d'exemple », #384) passe par le harnais partagé.
Lecture de l'arbre rendu — `src/test/elementTree.ts` (#467). `find(node, pred)` rend tous les éléments que garde le prédicat, en profondeur (un élément avant ce qu'il contient), à travers les tableaux, à toute profondeur, et les fragments ; `find(tree, (el) => el.type === CategoryForm)` rend les éléments d'un type. `holding(node, type)` rend les éléments dont un enfant direct est un élément de ce type, chacun une fois : le bouton qui porte un `Trash2`, ni l'icône ni la ligne autour du bouton ; un tableau de `props.children` n'y est lu que sur un niveau. Les deux ne lisent que `props.children`, et un composant enfant reste un élément : son bouton s'atteint par les props de son élément (`props.onDelete()` de `CategoryForm`). Chaque point est prouvé par `src/test/elementTree.test.ts`. L'utilisent au 2026-10-23 `ProfileFormModal.delete.test.ts`, `BudgetPage.wiring.test.ts` et les quatre tests de suppression de #467 ; seize autres fichiers de test gardent leur propre copie de `find` ou de `holding`, que `grep -rlE "function (find|holding)\(" src --include='*.test.*'` liste.
### Faux `t` marqué — `src/test/i18nMock.ts` (#389)

View file

@ -0,0 +1,96 @@
// AdjustmentDetailPanel — deleting an adjustment waits for the confirmation (#421, #467).
//
// Without its `await`, `!(await confirmAction(…))` would test a Promise, always
// truthy: the adjustment would go before the user answered, and "Cancel" would
// stop nothing. `native-dialog-guard.test.ts` checks the `await` in the source;
// this test checks what the handler does with the answer. The panel runs as a
// plain function under the shared hook harness (#409). Its delete button lives
// in the child AdjustmentForm (`onClick={onDelete}`), which the harness never
// calls: the test finds the AdjustmentForm element of the edit view and calls
// its `onDelete` prop, the panel's handler, with the confirmation answered by a
// mocked `confirmAction`.
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("react", async (orig) => (await import("../../test/hookHarness")).fakeReact(await orig()));
vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock());
const mocks = vi.hoisted(() => ({
confirmAction: vi.fn<(message: string) => Promise<boolean>>(),
}));
vi.mock("../../services/confirmService", () => ({ confirmAction: mocks.confirmAction }));
import { hookHarness } from "../../test/hookHarness";
import { find } from "../../test/elementTree";
import AdjustmentDetailPanel from "./AdjustmentDetailPanel";
import AdjustmentForm from "./AdjustmentForm";
import type { Adjustment } from "../../shared/types";
import type { AdjustmentFormData } from "../../hooks/useAdjustments";
const harness = hookHarness();
const CABIN: Adjustment = {
id: 7,
name: "Chalet",
description: "",
date: "2026-10-01",
is_recurring: false,
created_at: "",
updated_at: "",
};
const EDITING: AdjustmentFormData = { name: CABIN.name, description: "", date: CABIN.date, is_recurring: false };
const CONFIRM = "t(adjustments.deleteConfirm)";
let onDelete = vi.fn<(id: number) => void>();
/** One render of the mounted panel, in the edit view of the selected adjustment. */
const render = () =>
harness.render(() =>
AdjustmentDetailPanel({
selectedAdjustment: CABIN,
entries: [],
categories: [],
editingAdjustment: EDITING,
editingEntries: [],
isCreating: false,
isSaving: false,
onStartEditing: vi.fn(),
onCancelEditing: vi.fn(),
onSave: vi.fn(),
onDelete,
}),
);
/** Clicks the form's delete button, through the prop the panel hands the form, and waits for the handler. */
async function clickDelete() {
const forms = find(render(), (el) => el.type === AdjustmentForm);
expect(forms).toHaveLength(1);
await (forms[0].props.onDelete as () => Promise<void>)();
}
beforeEach(() => {
harness.clear();
mocks.confirmAction.mockReset();
onDelete = vi.fn<(id: number) => void>();
});
describe("AdjustmentDetailPanel deletion (#421, #467)", () => {
it("keeps the adjustment when the confirmation is refused", async () => {
mocks.confirmAction.mockResolvedValue(false);
await clickDelete();
expect(mocks.confirmAction).toHaveBeenCalledWith(CONFIRM);
expect(onDelete).not.toHaveBeenCalled();
});
it("deletes the selected adjustment once confirmed", async () => {
mocks.confirmAction.mockResolvedValue(true);
await clickDelete();
expect(mocks.confirmAction).toHaveBeenCalledWith(CONFIRM);
expect(onDelete).toHaveBeenCalledTimes(1);
expect(onDelete).toHaveBeenCalledWith(7);
});
});

View file

@ -0,0 +1,104 @@
// TemplateActions — deleting a budget template waits for the confirmation (#421, #467).
//
// Without its `await`, `if (await confirmAction(…))` would test a Promise,
// always truthy: the template would go before the user answered, and "Cancel"
// would stop nothing. `native-dialog-guard.test.ts` checks the `await` in the
// source; this test checks what the handler does with the answer. The
// component runs as a plain function under the shared hook harness (#409). The
// test opens the template list by its button, as the user does, renders again,
// then calls the `onClick` of a template's delete button with a fake event,
// the confirmation answered by a mocked `confirmAction`. No slot is preset, so
// the test does not depend on the order of the component's hooks.
//
// Never `harness.commit()`: the component's effect calls
// `document.addEventListener`, and vitest's node environment has no `document`.
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("react", async (orig) => (await import("../../test/hookHarness")).fakeReact(await orig()));
vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock());
const mocks = vi.hoisted(() => ({
confirmAction: vi.fn<(message: string) => Promise<boolean>>(),
}));
vi.mock("../../services/confirmService", () => ({ confirmAction: mocks.confirmAction }));
import { BookTemplate, Trash2 } from "lucide-react";
import { hookHarness } from "../../test/hookHarness";
import { holding } from "../../test/elementTree";
import TemplateActions from "./TemplateActions";
import type { BudgetTemplate } from "../../shared/types";
const harness = hookHarness();
const SUMMER: BudgetTemplate = { id: 4, name: "Été", created_at: "" };
const WINTER: BudgetTemplate = { id: 9, name: "Hiver", created_at: "" };
const CONFIRM = "t(budget.deleteTemplateConfirm)";
let onDelete = vi.fn<(templateId: number) => void>();
/** One render of the mounted component. */
const render = () =>
harness.render(() =>
TemplateActions({
templates: [SUMMER, WINTER],
onApply: vi.fn(),
onApplyAllMonths: vi.fn(),
onSave: vi.fn(),
onDelete,
}),
);
/** Opens the template list by its button, then renders the open list. */
function openList() {
const toggles = holding(render(), BookTemplate);
expect(toggles).toHaveLength(1);
(toggles[0].props.onClick as () => void)();
return render();
}
type FakeEvent = { stopPropagation: ReturnType<typeof vi.fn> };
/**
* Clicks the delete button of the second template and waits for the handler.
* The event's propagation must stop before the answer: the click would
* otherwise reach the row, which selects the template.
*/
async function clickDeleteOfWinter(): Promise<FakeEvent> {
const buttons = holding(openList(), Trash2);
expect(buttons).toHaveLength(2);
const event: FakeEvent = { stopPropagation: vi.fn() };
const handled = (buttons[1].props.onClick as (e: FakeEvent) => Promise<void>)(event);
expect(event.stopPropagation).toHaveBeenCalledTimes(1);
await handled;
return event;
}
beforeEach(() => {
harness.clear();
mocks.confirmAction.mockReset();
onDelete = vi.fn<(templateId: number) => void>();
});
describe("TemplateActions template deletion (#421, #467)", () => {
it("keeps the template when the confirmation is refused, and stops the click there", async () => {
mocks.confirmAction.mockResolvedValue(false);
const event = await clickDeleteOfWinter();
expect(mocks.confirmAction).toHaveBeenCalledWith(CONFIRM);
expect(onDelete).not.toHaveBeenCalled();
expect(event.stopPropagation).toHaveBeenCalledTimes(1);
});
it("deletes the template of the button once confirmed, and stops the click there", async () => {
mocks.confirmAction.mockResolvedValue(true);
const event = await clickDeleteOfWinter();
expect(mocks.confirmAction).toHaveBeenCalledWith(CONFIRM);
expect(onDelete).toHaveBeenCalledTimes(1);
expect(onDelete).toHaveBeenCalledWith(WINTER.id);
expect(event.stopPropagation).toHaveBeenCalledTimes(1);
});
});

View file

@ -0,0 +1,149 @@
// CategoryDetailPanel — deleting a category waits for the confirmation (#421, #467).
//
// Without its `await`, `!(await confirmAction(…))` would test a Promise, always
// truthy: the category would go before the user answered, and "Cancel" would
// stop nothing. `native-dialog-guard.test.ts` checks the `await` in the source;
// this test checks what the handler does with the answer. The panel runs as a
// plain function under the shared hook harness (#409). Its delete button lives
// in the child CategoryForm (`onClick={onDelete}`), which the harness never
// calls: the test finds the CategoryForm element of the edit view and calls its
// `onDelete` prop, the panel's handler, with the confirmation answered by a
// mocked `confirmAction`. The tests that render this panel with the real React
// stay in CategoryDetailPanel.render.test.tsx: a mock of "react" for the whole
// file would break them.
import { describe, it, expect, vi, beforeEach } from "vitest";
import 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());
const mocks = vi.hoisted(() => ({
confirmAction: vi.fn<(message: string) => Promise<boolean>>(),
}));
vi.mock("../../services/confirmService", () => ({ confirmAction: mocks.confirmAction }));
import { hookHarness } from "../../test/hookHarness";
import { find } from "../../test/elementTree";
import CategoryDetailPanel from "./CategoryDetailPanel";
import CategoryForm from "./CategoryForm";
import type { CategoryFormData, CategoryTreeNode } from "../../shared/types";
const harness = hookHarness();
/** A category whose numbers all differ from its id, so that only the id passes for it. */
const node = (id: number, parent_id: number | null, name: string, sort_order: number): CategoryTreeNode => ({
id,
name,
parent_id,
color: null,
icon: null,
type: "expense",
is_active: true,
is_inputable: true,
sort_order,
keyword_count: 4,
i18n_key: null,
children: [],
});
const HOUSING = node(1, null, "Logement", 1);
const RENT = node(10, 1, "Loyer", 2);
const EDITING: CategoryFormData = {
name: RENT.name,
type: RENT.type,
color: "#4A90A4",
parent_id: RENT.parent_id,
is_inputable: true,
sort_order: RENT.sort_order,
};
const CONFIRM = "t(categories.deleteConfirm)";
/** What the panel says when the service refuses: the category still carries 3 transactions. */
const BLOCKED = "t(categories.deleteBlocked[count=3])";
type DeleteResult = { blocked: boolean; count: number };
let onDelete = vi.fn<(id: number) => Promise<DeleteResult>>();
/** One render of the mounted panel, in the edit view of the selected category. */
const render = () =>
harness.render(() =>
CategoryDetailPanel({
categories: [HOUSING, RENT],
selectedCategory: RENT,
keywords: [],
editingCategory: EDITING,
isCreating: false,
isSaving: false,
onStartEditing: vi.fn(),
onCancelEditing: vi.fn(),
onSave: vi.fn(),
onDelete,
onAddKeyword: vi.fn(),
onUpdateKeyword: vi.fn(),
onRemoveKeyword: vi.fn(),
}),
);
/** Clicks the form's delete button, through the prop the panel hands the form, and waits for the handler. */
async function clickDelete() {
const forms = find(render(), (el) => el.type === CategoryForm);
expect(forms).toHaveLength(1);
await (forms[0].props.onDelete as () => Promise<void>)();
}
/** The texts the tree renders as the whole content of an element. */
const texts = (tree: ReactNode) =>
find(tree, (el) => typeof el.props.children === "string").map((el) => el.props.children as string);
beforeEach(() => {
harness.clear();
mocks.confirmAction.mockReset();
onDelete = vi.fn<(id: number) => Promise<DeleteResult>>(async () => ({ blocked: false, count: 0 }));
});
describe("CategoryDetailPanel deletion (#421, #467)", () => {
it("keeps the category when the confirmation is refused", async () => {
mocks.confirmAction.mockResolvedValue(false);
await clickDelete();
expect(mocks.confirmAction).toHaveBeenCalledWith(CONFIRM);
expect(onDelete).not.toHaveBeenCalled();
});
it("deletes the selected category once confirmed, and says nothing more", async () => {
mocks.confirmAction.mockResolvedValue(true);
await clickDelete();
expect(mocks.confirmAction).toHaveBeenCalledWith(CONFIRM);
expect(onDelete).toHaveBeenCalledTimes(1);
expect(onDelete).toHaveBeenCalledWith(10);
expect(texts(render()).filter((text) => text.includes("categories.deleteBlocked"))).toEqual([]);
});
it("says why at the next render when the service refuses the deletion", async () => {
mocks.confirmAction.mockResolvedValue(true);
onDelete.mockResolvedValue({ blocked: true, count: 3 });
expect(texts(render())).not.toContain(BLOCKED);
await clickDelete();
expect(mocks.confirmAction).toHaveBeenCalledWith(CONFIRM);
expect(onDelete).toHaveBeenCalledWith(10);
expect(texts(render())).toContain(BLOCKED);
});
it("clears that message once a later deletion goes through", async () => {
mocks.confirmAction.mockResolvedValue(true);
onDelete.mockResolvedValueOnce({ blocked: true, count: 3 });
await clickDelete();
expect(texts(render())).toContain(BLOCKED);
await clickDelete();
expect(mocks.confirmAction).toHaveBeenCalledTimes(2);
expect(mocks.confirmAction).toHaveBeenLastCalledWith(CONFIRM);
expect(texts(render())).not.toContain(BLOCKED);
});
});

View file

@ -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<string, unknown> & { children?: ReactNode; onClick?: () => Promise<void> };
/** The elements of the tree whose children hold an element of the given type. */
function holding(node: ReactNode, type: unknown): ReactElement<Props>[] {
if (Array.isArray(node)) return node.flatMap((n) => holding(n, type));
if (!isValidElement(node)) return [];
const el = node as ReactElement<Props>;
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<void> };
/** 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<Props>(tree, Trash2);
expect(buttons).toHaveLength(1);
await buttons[0].props.onClick?.();
}

View file

@ -0,0 +1,189 @@
// AccountsPage — deleting a balance category waits for the confirmation (#421, #467).
//
// Without its `await`, `!(await confirmAction(…))` would test a Promise, always
// truthy: the category would go before the user answered, and "Cancel" would
// stop nothing. `native-dialog-guard.test.ts` checks the `await` in the source;
// this test checks what the handler does with the answer, and that the guards
// placed before the dialog (a seeded category, one with linked accounts) open
// no dialog. The page runs as a plain function under the shared hook harness
// (#409), with `useBalanceAccounts` mocked as a whole. The test opens the
// categories tab by its button, as the user does, renders again, then calls
// the `onClick` of a category's delete button, the confirmation answered by a
// mocked `confirmAction`. No slot is preset, so the test does not depend on
// the order of the page's hooks.
//
// The delete button of a seeded category or of one with linked accounts is
// disabled, so no click reaches its handler in the app; the test calls the
// handler through the props anyway, to prove the guard behind the button.
import { describe, it, expect, vi, beforeEach } from "vitest";
import 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());
const ctx = vi.hoisted(() => ({ balance: null as unknown }));
const mocks = vi.hoisted(() => ({
confirmAction: vi.fn<(message: string) => Promise<boolean>>(),
}));
vi.mock("../services/confirmService", () => ({ confirmAction: mocks.confirmAction }));
vi.mock("../hooks/useBalanceAccounts", () => ({ useBalanceAccounts: () => ctx.balance }));
import { Trash2 } from "lucide-react";
import { hookHarness } from "../test/hookHarness";
import { find, holding } from "../test/elementTree";
import AccountsPage from "./AccountsPage";
import type { BalanceAccountWithCategory, BalanceCategory } from "../shared/types";
const harness = hookHarness();
/** A balance category; its sort order differs from its id, so that only the id passes for it. */
const category = (id: number, key: string, sort_order: number, is_seed = false): BalanceCategory => ({
id,
key,
i18n_key: `balance.category.${key}`,
kind: "simple",
sort_order,
is_active: true,
is_seed,
asset_type: null,
custom_label: null,
});
/** A category of the user, without any account: the only one the page lets go. */
const BOAT = category(21, "boat", 1);
/** A category of the user, two accounts linked to it. */
const ART = category(22, "art", 2);
/** A category of the seed, protected. */
const CASH = category(23, "cash", 3, true);
const account = (id: number, name: string, cat: BalanceCategory): BalanceAccountWithCategory => ({
id,
balance_category_id: cat.id,
name,
symbol: null,
currency: "CAD",
notes: null,
is_active: true,
archived_at: null,
vehicle_type: null,
kind: "simple",
detailed_since: null,
created_at: "",
updated_at: "",
category_key: cat.key,
category_i18n_key: cat.i18n_key,
category_kind: cat.kind,
category_asset_type: null,
category_custom_label: null,
});
const CONFIRM = "t(balance.category.actions.deleteConfirm)";
const HAS_ACCOUNTS = "t(balance.category.error.has_accounts[count=2,names=Voilier, Toile])";
let removeCategory = vi.fn<(id: number) => Promise<void>>();
/** One render of the mounted page. */
const render = () => harness.render(() => AccountsPage());
/** Opens the categories tab by its button, then renders the open tab. */
function openCategories() {
const tabs = find(
render(),
(el) => el.type === "button" && el.props.children === "t(balance.accountsPage.tabs.categories)",
);
expect(tabs).toHaveLength(1);
(tabs[0].props.onClick as () => void)();
return render();
}
/** The delete button of a category's row. */
function deleteButton(tree: ReactNode, cat: BalanceCategory) {
const rows = find(tree, (el) => el.type === "tr" && el.key === String(cat.id));
expect(rows).toHaveLength(1);
const buttons = holding(rows[0], Trash2);
expect(buttons).toHaveLength(1);
return buttons[0];
}
/** Clicks a category's delete button, through its props, and waits for the handler. */
async function clickDelete(button: ReturnType<typeof deleteButton>) {
await (button.props.onClick as () => Promise<void>)();
}
/** The texts the tree renders as the whole content of an element. */
const texts = (tree: ReactNode) =>
find(tree, (el) => typeof el.props.children === "string").map((el) => el.props.children as string);
beforeEach(() => {
harness.clear();
mocks.confirmAction.mockReset();
removeCategory = vi.fn<(id: number) => Promise<void>>(async () => undefined);
ctx.balance = {
state: {
categories: [BOAT, ART, CASH],
accounts: [account(1, "Voilier", ART), account(2, "Toile", ART)],
includeArchived: false,
isLoading: false,
isSaving: false,
error: null,
errorCode: null,
},
setIncludeArchived: vi.fn(),
refresh: vi.fn(),
addAccount: vi.fn(),
editAccount: vi.fn(),
archiveAccount: vi.fn(),
unarchiveAccount: vi.fn(),
addCategory: vi.fn(),
editCategory: vi.fn(),
removeCategory,
};
});
describe("AccountsPage balance category deletion (#421, #467)", () => {
it("keeps the category when the confirmation is refused", async () => {
mocks.confirmAction.mockResolvedValue(false);
const button = deleteButton(openCategories(), BOAT);
expect(button.props.disabled).toBe(false);
await clickDelete(button);
expect(mocks.confirmAction).toHaveBeenCalledWith(CONFIRM);
expect(removeCategory).not.toHaveBeenCalled();
});
it("deletes the category once confirmed", async () => {
mocks.confirmAction.mockResolvedValue(true);
await clickDelete(deleteButton(openCategories(), BOAT));
expect(mocks.confirmAction).toHaveBeenCalledWith(CONFIRM);
expect(removeCategory).toHaveBeenCalledTimes(1);
expect(removeCategory).toHaveBeenCalledWith(BOAT.id);
});
it("opens no dialog for a category with linked accounts, and says why at the next render", async () => {
mocks.confirmAction.mockResolvedValue(true);
const button = deleteButton(openCategories(), ART);
expect(button.props.disabled).toBe(true);
expect(texts(render())).not.toContain(HAS_ACCOUNTS);
await clickDelete(button);
expect(mocks.confirmAction).not.toHaveBeenCalled();
expect(removeCategory).not.toHaveBeenCalled();
expect(texts(render())).toContain(HAS_ACCOUNTS);
});
it("does nothing for a seeded category: no dialog, no message", async () => {
mocks.confirmAction.mockResolvedValue(true);
const button = deleteButton(openCategories(), CASH);
expect(button.props.disabled).toBe(true);
await clickDelete(button);
expect(mocks.confirmAction).not.toHaveBeenCalled();
expect(removeCategory).not.toHaveBeenCalled();
expect(texts(render()).filter((text) => text.includes("balance.category.error"))).toEqual([]);
});
});

View file

@ -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<Record<string, unknown> & { 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,

View file

@ -0,0 +1,136 @@
// 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("never calls a component of the tree: a holder its child renders is not there", () => {
const Child = vi.fn(() => h("button", { id: "inside" }, h(Trash2)));
const node = h("div", { id: "d" }, h(Child));
expect(holding(node, Trash2)).toEqual([]);
expect(ids(holding(node, Child))).toEqual(["d"]);
expect(Child).not.toHaveBeenCalled();
});
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([]);
});
});

55
src/test/elementTree.ts Normal file
View file

@ -0,0 +1,55 @@
// 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, shared since #467 (several
// test files still keep a copy of their own). 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 `<td>{rows}</td>` the items of `rows` are direct children of the cell,
// in `<td>{label}{rows}</td>` they are not. A fragment holds its own
// children, not its parent.
//
// Both read `props.children` only: an element passed in another prop
// (`icon={<Plus />}`) 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<string, unknown> & { children?: ReactNode };
/** An element of the tree; `P` narrows its props for a test that knows them. */
export type TreeElement<P extends TreeProps = TreeProps> = ReactElement<P>;
/** Every element of `node` for which `pred` is true, depth first, through arrays and fragments. */
export function find<P extends TreeProps = TreeProps>(
node: ReactNode,
pred: (el: TreeElement<P>) => boolean,
): TreeElement<P>[] {
if (Array.isArray(node)) return node.flatMap((n) => find(n, pred));
if (!isValidElement(node)) return [];
const el = node as TreeElement<P>;
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<P extends TreeProps = TreeProps>(node: ReactNode, type: unknown): TreeElement<P>[] {
if (Array.isArray(node)) return node.flatMap((n) => holding<P>(n, type));
if (!isValidElement(node)) return [];
const el = node as TreeElement<P>;
const children = ([] as ReactNode[]).concat(el.props.children ?? []);
const holds = children.some((c) => isValidElement(c) && c.type === type);
return [...(holds ? [el] : []), ...holding<P>(el.props.children, type)];
}