Simpl-Resultat/src/hooks/useCategories.test.ts
le king fu 13dca87d04 test(categories): a failed re-read of the categories shows in the window (#393)
Review 25974, suggestion 1 (Q6): the JSDoc, architecture.md and the PR
body say a failure of readCategoriesAgain shows in the hierarchy window,
and no test held it. The read is rejected once at the opening (the
diagnostic does not run on the old categories) and once after a
committed reattachment: each time the window shows the message, the
page's banner behind it stays empty, and saving is over.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 20:15:05 -04:00

382 lines
17 KiB
TypeScript

// useCategories — the hierarchy check and its refusals (#393).
//
// React's hooks come from the shared harness (src/test/hookHarness.ts, #409):
// the hook runs as a plain function, its reducer is applied, `commit()` runs
// its mount effect. The service is mocked, except the refusal class and its
// i18n key, which the hook must recognize by `instanceof`.
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("react", async (orig) => (await import("../test/hookHarness")).fakeReact(await orig()));
vi.mock("../services/categoryService", async (importOriginal) => {
const actual = await importOriginal<typeof import("../services/categoryService")>();
return {
CategoryHierarchyError: actual.CategoryHierarchyError,
categoryHierarchyErrorKey: actual.categoryHierarchyErrorKey,
getAllCategoriesWithCounts: vi.fn(),
createCategory: vi.fn(),
updateCategory: vi.fn(),
deactivateCategory: vi.fn(),
getCategoryUsageCount: vi.fn(),
getChildrenUsageCount: vi.fn(),
getKeywordsByCategoryId: vi.fn(async () => []),
createKeyword: vi.fn(),
updateKeyword: vi.fn(),
deactivateKeyword: vi.fn(),
reinitializeCategories: vi.fn(),
hasDuplicateSortOrders: vi.fn(async () => false),
fixDuplicateSortOrders: vi.fn(),
getNextSortOrder: vi.fn(),
updateCategorySortOrders: vi.fn(),
findOrphanCategories: vi.fn(),
reattachCategory: vi.fn(),
};
});
vi.mock("../services/logService", () => ({ logInfo: vi.fn(), logWarn: vi.fn(), logError: vi.fn() }));
import { hookHarness } from "../test/hookHarness";
import {
useCategories,
categoriesErrorOf,
categoriesErrorText,
reattachLogLine,
} from "./useCategories";
import {
CategoryHierarchyError,
createCategory,
findOrphanCategories,
getAllCategoriesWithCounts,
reattachCategory,
updateCategory,
updateCategorySortOrders,
} from "../services/categoryService";
import { logInfo } from "../services/logService";
import { markedT } from "../test/i18nMock";
import type { OrphanCategory } from "../utils/categoryHierarchy";
const harness = hookHarness();
const ROWS = [
{ id: 1, name: "Logement", parent_id: null, color: null, icon: null, type: "expense", is_active: true, is_inputable: false, sort_order: 1, keyword_count: 0, i18n_key: null },
{ id: 10, name: "Loyer", parent_id: 1, color: null, icon: null, type: "expense", is_active: true, is_inputable: true, sort_order: 1, keyword_count: 0, i18n_key: null },
];
const CYCLE: OrphanCategory = { id: 3, reason: "cycle" };
/** Lets the hook's promises settle. */
const flush = async () => {
for (let i = 0; i < 20; i++) await Promise.resolve();
};
/** Mounts the hook and lets its first load settle. */
async function mount() {
harness.render(useCategories);
harness.commit();
await flush();
return harness.render(useCategories);
}
const FORM = { name: "Logement", type: "expense" as const, color: "#4A90A4", parent_id: 10, is_inputable: false, sort_order: 1 };
beforeEach(() => {
harness.clear();
vi.mocked(getAllCategoriesWithCounts).mockReset();
vi.mocked(getAllCategoriesWithCounts).mockResolvedValue(ROWS as never);
vi.mocked(updateCategory).mockReset();
vi.mocked(createCategory).mockReset();
vi.mocked(findOrphanCategories).mockReset();
vi.mocked(reattachCategory).mockReset();
vi.mocked(updateCategorySortOrders).mockReset();
vi.mocked(updateCategorySortOrders).mockResolvedValue(undefined);
vi.mocked(logInfo).mockReset();
});
describe("categoriesErrorOf / categoriesErrorText (#393)", () => {
it("names a hierarchy refusal by the i18n key of its code, never by its message", () => {
const error = categoriesErrorOf(new CategoryHierarchyError("cycle", "raw text"));
expect(error).toEqual({ key: "categories.hierarchy.errors.cycle" });
expect(categoriesErrorText(error, markedT)).toBe("t(categories.hierarchy.errors.cycle)");
});
it("names the refusals of a parent's budget amounts and keywords by their keys (decision of 2026-10-19)", () => {
expect(categoriesErrorOf(new CategoryHierarchyError("parent_has_budget"))).toEqual({
key: "categories.hierarchy.errors.parent_has_budget",
});
expect(categoriesErrorOf(new CategoryHierarchyError("parent_has_keywords"))).toEqual({
key: "categories.hierarchy.errors.parent_has_keywords",
});
});
it("keeps the message of any other failure", () => {
const error = categoriesErrorOf(new Error("database is locked"));
expect(error).toEqual({ message: "database is locked" });
expect(categoriesErrorText(error, markedT)).toBe("database is locked");
expect(categoriesErrorOf("boom")).toEqual({ message: "boom" });
});
});
describe("useCategories — saving the form (#393)", () => {
it("shows a refused parent by its translated code, and keeps the form open", async () => {
vi.mocked(updateCategory).mockRejectedValue(new CategoryHierarchyError("cycle"));
let api = await mount();
await api.selectCategory(1);
api = harness.render(useCategories);
api.startEditing();
api = harness.render(useCategories);
await api.saveCategory(FORM);
const { state } = harness.render(useCategories);
expect(updateCategory).toHaveBeenCalledWith(1, FORM);
expect(state.error).toEqual({ key: "categories.hierarchy.errors.cycle" });
expect(state.isSaving).toBe(false);
expect(state.editingCategory).not.toBeNull();
});
it("shows a refused sub-category by its translated code, and keeps the creation form open", async () => {
vi.mocked(createCategory).mockRejectedValue(new CategoryHierarchyError("parent_has_keywords"));
let api = await mount();
api.startCreating();
api = harness.render(useCategories);
const child = { ...FORM, name: "Électricité", parent_id: 10 };
await api.saveCategory(child);
const { state } = harness.render(useCategories);
expect(createCategory).toHaveBeenCalledWith(expect.objectContaining({ name: "Électricité", parent_id: 10 }));
expect(state.error).toEqual({ key: "categories.hierarchy.errors.parent_has_keywords" });
expect(state.isSaving).toBe(false);
expect(state.isCreating).toBe(true);
expect(state.editingCategory).not.toBeNull();
});
it("shows any other failure by its message", async () => {
vi.mocked(updateCategory).mockRejectedValue(new Error("database is locked"));
let api = await mount();
await api.selectCategory(1);
api = harness.render(useCategories);
await api.saveCategory(FORM);
expect(harness.render(useCategories).state.error).toEqual({ message: "database is locked" });
});
});
describe("useCategories — « Vérifier la hiérarchie » (#393)", () => {
it("opens the window while the check runs, then lists the orphans", async () => {
let resolve: (orphans: OrphanCategory[]) => void = () => undefined;
vi.mocked(findOrphanCategories).mockReturnValue(new Promise((r) => (resolve = r)));
const api = await mount();
expect(api.state.hierarchyCheck).toBeNull();
const done = api.checkHierarchy();
expect(harness.render(useCategories).state.hierarchyCheck).toEqual({ orphans: null, error: null });
resolve([CYCLE]);
await done;
expect(harness.render(useCategories).state.hierarchyCheck).toEqual({ orphans: [CYCLE], error: null });
});
it("shows a check that failed in the window", async () => {
vi.mocked(findOrphanCategories).mockRejectedValue(new Error("database is locked"));
const api = await mount();
await api.checkHierarchy();
expect(harness.render(useCategories).state.hierarchyCheck).toEqual({
orphans: null,
error: { message: "database is locked" },
});
});
it("reattaches, writes one Journal line without any name, then reloads the list and the tree", async () => {
vi.mocked(findOrphanCategories).mockResolvedValueOnce([CYCLE]).mockResolvedValueOnce([]);
vi.mocked(reattachCategory).mockResolvedValue(3);
let api = await mount();
await api.checkHierarchy();
api = harness.render(useCategories);
// The mount's read, then the check's.
expect(getAllCategoriesWithCounts).toHaveBeenCalledTimes(2);
await api.reattachOrphan(CYCLE, 1);
expect(reattachCategory).toHaveBeenCalledWith(3, 1);
expect(logInfo).toHaveBeenCalledTimes(1);
const line = vi.mocked(logInfo).mock.calls[0][0] as string;
expect(line).toBe(reattachLogLine("cycle", 3));
expect(line).toContain("3 categories");
for (const row of ROWS) expect(line).not.toContain(row.name);
expect(findOrphanCategories).toHaveBeenCalledTimes(2);
expect(getAllCategoriesWithCounts).toHaveBeenCalledTimes(3);
const { state } = harness.render(useCategories);
expect(state.hierarchyCheck).toEqual({ orphans: [], error: null });
expect(state.isSaving).toBe(false);
});
it("reloads the tree even when the check after a committed reattachment fails", async () => {
vi.mocked(findOrphanCategories)
.mockResolvedValueOnce([CYCLE])
.mockRejectedValueOnce(new Error("database is locked"));
vi.mocked(reattachCategory).mockResolvedValue(2);
let api = await mount();
await api.checkHierarchy();
api = harness.render(useCategories);
await api.reattachOrphan(CYCLE, null);
expect(reattachCategory).toHaveBeenCalledWith(3, null);
expect(logInfo).toHaveBeenCalledTimes(1);
// The mount's read, the check's, and the reload after the committed reattachment.
expect(getAllCategoriesWithCounts).toHaveBeenCalledTimes(3);
const { state } = harness.render(useCategories);
expect(state.hierarchyCheck?.error).toEqual({ message: "database is locked" });
expect(state.isSaving).toBe(false);
});
it("shows a refused reattachment in the window by its translated code, with no Journal line", async () => {
vi.mocked(findOrphanCategories).mockResolvedValue([CYCLE]);
vi.mocked(reattachCategory).mockRejectedValue(new CategoryHierarchyError("parent_has_transactions"));
let api = await mount();
await api.checkHierarchy();
api = harness.render(useCategories);
await api.reattachOrphan(CYCLE, 1);
const { state } = harness.render(useCategories);
expect(state.hierarchyCheck).toEqual({
orphans: [CYCLE],
error: { key: "categories.hierarchy.errors.parent_has_transactions" },
});
expect(state.error).toBeNull();
expect(state.isSaving).toBe(false);
expect(logInfo).not.toHaveBeenCalled();
});
it("a refusal, then a reattachment that goes through: the window's message goes", async () => {
vi.mocked(findOrphanCategories).mockResolvedValueOnce([CYCLE]).mockResolvedValueOnce([]);
vi.mocked(reattachCategory)
.mockRejectedValueOnce(new CategoryHierarchyError("parent_has_transactions"))
.mockResolvedValueOnce(3);
let api = await mount();
await api.checkHierarchy();
api = harness.render(useCategories);
await api.reattachOrphan(CYCLE, 1);
api = harness.render(useCategories);
expect(api.state.hierarchyCheck?.error).toEqual({ key: "categories.hierarchy.errors.parent_has_transactions" });
await api.reattachOrphan(CYCLE, null);
expect(harness.render(useCategories).state.hierarchyCheck).toEqual({ orphans: [], error: null });
});
it("after a drag-and-drop, reads the categories again: the window gets the members of a loop back", async () => {
// 1 with 10 under it, 2, and 3 <-> 5: no root reaches 3 nor 5.
const row = (id: number, parent_id: number | null) => ({ ...ROWS[1], id, name: `c${id}`, parent_id, sort_order: id });
vi.mocked(getAllCategoriesWithCounts).mockResolvedValue([
row(1, null),
row(10, 1),
row(2, null),
row(3, 5),
row(5, 3),
] as never);
vi.mocked(findOrphanCategories).mockResolvedValue([CYCLE]);
let api = await mount();
const ids = () => harness.render(useCategories).state.categories.map((c) => c.id).sort((a, b) => a - b);
expect(ids()).toEqual([1, 2, 3, 5, 10]);
await api.moveCategory(2, null, 0);
// The drag-and-drop keeps what the tree shows: the loop is gone from the list.
expect(ids()).toEqual([1, 2, 10]);
api = harness.render(useCategories);
harness.dispatch.mockClear();
await api.checkHierarchy();
expect(ids()).toEqual([1, 2, 3, 5, 10]);
expect(harness.render(useCategories).state.hierarchyCheck).toEqual({ orphans: [CYCLE], error: null });
// Read without the page's loading state: the tree and an open form stay on screen.
const types = harness.dispatch.mock.calls.map(([action]) => (action as { type: string }).type);
expect(types).not.toContain("SET_LOADING");
});
it("lets a load started during the check's read win over it", async () => {
let answer: (rows: unknown) => void = () => undefined;
const NEWER = [...ROWS, { ...ROWS[0], id: 2, name: "Épargne", sort_order: 2 }];
vi.mocked(findOrphanCategories).mockResolvedValue([]);
let api = await mount();
vi.mocked(getAllCategoriesWithCounts)
.mockReturnValueOnce(new Promise((r) => (answer = r)) as never)
.mockResolvedValueOnce(NEWER as never);
const checked = api.checkHierarchy();
await flush(); // the check's read is out, still unanswered
api = harness.render(useCategories);
await api.reinitializeCategories(); // a newer load: NEWER lands
answer(ROWS); // the check's older answer comes last
await checked;
const ids = harness.render(useCategories).state.categories.map((c) => c.id).sort((a, b) => a - b);
expect(ids).toEqual([1, 2, 10]);
});
it("a reattachment reads the categories again without the loading state: a form behind the window stays", async () => {
vi.mocked(findOrphanCategories).mockResolvedValueOnce([CYCLE]).mockResolvedValueOnce([]);
vi.mocked(reattachCategory).mockResolvedValue(3);
let api = await mount();
await api.checkHierarchy();
api = harness.render(useCategories);
harness.dispatch.mockClear();
await api.reattachOrphan(CYCLE, null);
const types = harness.dispatch.mock.calls.map(([action]) => (action as { type: string }).type);
expect(types).toContain("SET_CATEGORIES");
expect(types).not.toContain("SET_LOADING");
expect(getAllCategoriesWithCounts).toHaveBeenCalledTimes(3);
});
it("shows a failed read of the categories in the window, never in the page's banner behind it", async () => {
vi.mocked(findOrphanCategories).mockResolvedValueOnce([CYCLE]).mockResolvedValueOnce([]);
vi.mocked(reattachCategory).mockResolvedValue(3);
let api = await mount();
// At the opening: the diagnostic does not run on the old categories.
vi.mocked(getAllCategoriesWithCounts).mockRejectedValueOnce(new Error("database is locked"));
await api.checkHierarchy();
let state = harness.render(useCategories).state;
expect(state.hierarchyCheck).toEqual({ orphans: null, error: { message: "database is locked" } });
expect(state.error).toBeNull();
expect(findOrphanCategories).not.toHaveBeenCalled();
// After a committed reattachment.
api = harness.render(useCategories);
await api.checkHierarchy();
api = harness.render(useCategories);
vi.mocked(getAllCategoriesWithCounts).mockRejectedValueOnce(new Error("disk I/O error"));
await api.reattachOrphan(CYCLE, null);
state = harness.render(useCategories).state;
expect(reattachCategory).toHaveBeenCalledWith(3, null);
expect(state.hierarchyCheck).toEqual({ orphans: [], error: { message: "disk I/O error" } });
expect(state.error).toBeNull();
expect(state.isSaving).toBe(false);
});
it("reads the categories once the drag-and-drop's writes are over, never halfway", async () => {
let written: () => void = () => undefined;
vi.mocked(updateCategorySortOrders).mockReturnValue(new Promise<void>((r) => (written = r)));
vi.mocked(findOrphanCategories).mockResolvedValue([]);
let api = await mount();
const moved = api.moveCategory(10, null, 0);
api = harness.render(useCategories);
const checked = api.checkHierarchy();
await flush();
// The mount's read only: the check waits for the writes.
expect(getAllCategoriesWithCounts).toHaveBeenCalledTimes(1);
expect(findOrphanCategories).not.toHaveBeenCalled();
written();
await Promise.all([moved, checked]);
expect(getAllCategoriesWithCounts).toHaveBeenCalledTimes(2);
expect(harness.render(useCategories).state.hierarchyCheck).toEqual({ orphans: [], error: null });
});
it("closes the window; a check that ends after it closed changes nothing", async () => {
let resolve: (orphans: OrphanCategory[]) => void = () => undefined;
vi.mocked(findOrphanCategories).mockReturnValue(new Promise((r) => (resolve = r)));
let api = await mount();
const done = api.checkHierarchy();
api = harness.render(useCategories);
api.closeHierarchyCheck();
resolve([CYCLE]);
await done;
expect(harness.render(useCategories).state.hierarchyCheck).toBeNull();
});
});
describe("reattachLogLine (#393)", () => {
it("gives the reason code and the count, singular or plural", () => {
expect(reattachLogLine("inactive_parent", 1)).toBe(
"Categories: orphan category reattached (inactive_parent), 1 category back in the hierarchy",
);
expect(reattachLogLine("cycle", 4)).toBe(
"Categories: orphan category reattached (cycle), 4 categories back in the hierarchy",
);
});
});