test: pin what four confirmation sites do with the answer (#467)

native-dialog-guard.test.ts checks that each confirmAction( is awaited, not what the handler does once the user answers. Behaviour tests on the hook harness for the four sites it alone held: CategoryDetailPanel (and the deleteBlocked message at the next render), AdjustmentDetailPanel, TemplateActions (stopPropagation before the answer, never commit()) and AccountsPage (a seeded category or one with linked accounts opens no dialog). Each refusal leaves the data alone, each acceptance deletes the right id, and each asserts the marked message passed to confirmAction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
le king fu 2026-10-23 21:00:13 -04:00
commit fdcca057cd
4 changed files with 536 additions and 0 deletions

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,148 @@
// 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();
const node = (id: number, parent_id: number | null, name: string): CategoryTreeNode => ({
id,
name,
parent_id,
color: null,
icon: null,
type: "expense",
is_active: true,
is_inputable: true,
sort_order: id,
keyword_count: 0,
i18n_key: null,
children: [],
});
const HOUSING = node(1, null, "Logement");
const RENT = node(10, 1, "Loyer");
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

@ -0,0 +1,188 @@
// 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();
const category = (id: number, key: string, is_seed = false): BalanceCategory => ({
id,
key,
i18n_key: `balance.category.${key}`,
kind: "simple",
sort_order: id,
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");
/** A category of the user, two accounts linked to it. */
const ART = category(22, "art");
/** A category of the seed, protected. */
const CASH = category(23, "cash", 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([]);
});
});