Simpl-Resultat/src/hooks/useImportWizard.samples.test.ts
le king fu 48d1314d6d fix(import): clear the error banner when the folder is read again (#384)
Review 25592, point 2 (pre-existing): the banner of a refused sample
folder asks to refresh the list, yet survived a "Refresh" that went
through, and a folder change. refreshFolder, and browseFolder once a
folder is chosen, now clear the error before reading the folder, as
selectSource does; a failed rescan puts up its own error, and a
cancelled picker keeps the banner. The hook tests also pin browseFolder's
order (review 25487, point 1): the folder is set before its scan, so the
root files shown are the new folder's. Fixed entry in both changelogs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 21:09:01 -04:00

243 lines
10 KiB
TypeScript

// useImportWizard — "Create a sample folder", its banners and its Journal line (#384).
//
// 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
// the mount read of the import folder (and its first scan), and the test then
// calls `createSampleFolders` from the next render, as the page's button does.
// `invoke` answers per command; the Journal is the real log service.
//
// What is pinned: the success banner only after a rescan that went through
// (a failed rescan leaves its error alone on screen), a refusal of the Rust
// command shown by its translation key and values, any other message raw, and
// the Journal line of a refusal, which never carries the import folder's path
// or name (the Journal travels with a feedback report). Then the banner of a
// refusal once the folder is read again, by « Actualiser » (`refreshFolder`)
// or by another folder (`browseFolder`, which sets the folder before its
// scan, so the root files shown are the new folder's).
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
vi.mock("react", async (orig) => (await import("../test/hookHarness")).fakeReact(await orig()));
const ipc = vi.hoisted(() => ({
/** The stored import folder: its name must never reach the Journal. */
importFolder: "/home/jean/Relevés bancaires",
/**
* What each command answers, in call order: a value, or an Error or a string
* to reject with; `{ resolves: "…" }` for a command that resolves a string
* (`pick_folder`).
*/
answers: {} as Record<string, unknown[]>,
}));
vi.mock("@tauri-apps/api/core", () => ({
invoke: vi.fn(async (command: string) => {
const queue = ipc.answers[command] ?? [];
if (queue.length === 0) throw new Error(`unexpected command ${command}`);
const answer = queue.shift();
if (answer instanceof Error || typeof answer === "string") throw answer;
if (typeof answer === "object" && answer !== null && "resolves" in answer) return answer.resolves;
return answer;
}),
}));
vi.mock("../services/db", () => ({ getDb: vi.fn(), withTransaction: vi.fn() }));
vi.mock("../services/userPreferenceService", () => ({
getImportFolder: vi.fn(async () => ipc.importFolder),
setImportFolder: vi.fn(),
}));
vi.mock("../services/importSourceService", () => ({
getAllSources: vi.fn(async () => []),
getSourceByName: vi.fn(async () => null),
createSource: vi.fn(),
updateSource: vi.fn(),
}));
vi.mock("../services/importedFileService", () => ({
existsByHash: vi.fn(),
createImportedFile: vi.fn(),
updateFileStatus: vi.fn(),
getFilesBySourceId: vi.fn(async () => []),
}));
vi.mock("../services/importConfigTemplateService", () => ({
getAllTemplates: vi.fn(async () => []),
createTemplate: vi.fn(),
updateTemplate: vi.fn(),
deleteTemplate: vi.fn(),
}));
import { invoke } from "@tauri-apps/api/core";
import { hookHarness } from "../test/hookHarness";
import { useImportWizard } from "./useImportWizard";
import { clearLogs, getLogs, initLogCapture } from "../services/logService";
import type { ImportFolderScan } from "../shared/types";
const harness = hookHarness();
const IMPORT_FOLDER = ipc.importFolder;
const NAMES = ["Exemple Desjardins", "Exemple Tangerine"];
const EMPTY_SCAN: ImportFolderScan = { sources: [], root_files: [] };
const SAMPLE_SCAN: ImportFolderScan = {
sources: NAMES.map((name) => ({ folder_name: name, folder_path: `${IMPORT_FOLDER}/${name}`, files: [] })),
root_files: [],
};
/** Lets the hook's promises settle. */
const flush = async () => {
for (let i = 0; i < 20; i++) await Promise.resolve();
};
/** Mounts the wizard on IMPORT_FOLDER (read, then scanned empty) and returns its next render. */
async function mount() {
harness.render(useImportWizard);
harness.commit();
await flush();
return harness.render(useImportWizard);
}
/** Clicks "Create a sample folder" and returns the state after it. */
async function createSamples() {
const wizard = await mount();
expect(wizard.state.importFolder).toBe(IMPORT_FOLDER);
await wizard.createSampleFolders();
return harness.render(useImportWizard).state;
}
const journal = () => getLogs().map((l) => `${l.level}: ${l.message}`);
const created = () =>
harness.dispatch.mock.calls.filter(([a]) => (a as { type: string }).type === "SET_SAMPLE_CREATED");
beforeEach(() => {
harness.clear();
vi.mocked(invoke).mockClear();
initLogCapture();
clearLogs();
ipc.answers = { scan_import_folder: [EMPTY_SCAN] };
});
afterEach(() => {
harness.unmount();
});
describe("createSampleFolders — the banners (#384)", () => {
it("rescan went through: the success banner names the folders, no error", async () => {
ipc.answers.create_sample_import_folders = [NAMES];
ipc.answers.scan_import_folder.push(SAMPLE_SCAN);
const state = await createSamples();
expect(state.sampleCreated).toEqual(NAMES);
expect(state.scannedSources).toBe(SAMPLE_SCAN.sources);
expect(state.error).toBeNull();
expect(state.isLoading).toBe(false);
});
it("rescan failed: the error banner alone, never the success one", async () => {
ipc.answers.create_sample_import_folders = [NAMES];
ipc.answers.scan_import_folder.push(new Error(`Folder does not exist: ${IMPORT_FOLDER}`));
const state = await createSamples();
expect(state.sampleCreated).toBeNull();
expect(created()).toEqual([]);
expect(state.error).toBe(`Folder does not exist: ${IMPORT_FOLDER}`);
// The folders were written all the same: the Journal says so, by name.
expect(journal()).toContain("info: [import] Sample folders created: Exemple Desjardins, Exemple Tangerine");
// The rescan's error carries the path: it stays on screen, out of the Journal.
expect(journal().join("\n")).not.toContain("Relevés");
});
});
describe("createSampleFolders — a refusal (#384, D2)", () => {
it("a sample folder already there: its key and name, no scan, no success banner", async () => {
ipc.answers.create_sample_import_folders = ["sample_folder_exists:Exemple Desjardins"];
const state = await createSamples();
expect(state.error).toBe("import.empty.sampleErrors.folderExists");
expect(state.errorValues).toEqual({ name: "Exemple Desjardins" });
expect(state.sampleCreated).toBeNull();
expect(state.isLoading).toBe(false);
// The mount's scan only: a refused creation is not rescanned.
expect(vi.mocked(invoke).mock.calls.filter(([c]) => c === "scan_import_folder")).toHaveLength(1);
});
it.each([
["import_folder_missing", "import.empty.sampleErrors.importFolderMissing"],
["invalid_date", "import.empty.sampleErrors.invalidDate"],
])("%s: its key, without values", async (code, key) => {
ipc.answers.create_sample_import_folders = [code];
const state = await createSamples();
expect(state.error).toBe(key);
expect(state.errorValues).toBeNull();
});
it("any other message is shown raw", async () => {
const raw = "Cannot write Exemple Desjardins/releve-2026-09.csv: Permission denied (os error 13)";
ipc.answers.create_sample_import_folders = [raw];
const state = await createSamples();
expect(state.error).toBe(raw);
expect(state.errorValues).toBeNull();
});
it.each([
"sample_folder_exists:Exemple Tangerine",
"import_folder_missing",
"invalid_date",
"Cannot create folder Exemple Desjardins: Permission denied (os error 13)",
])("the Journal gets the raw refusal as a warning, never the import folder (%s)", async (raw) => {
ipc.answers.create_sample_import_folders = [raw];
await createSamples();
expect(journal()).toEqual([`warn: [import] Sample folders not created: ${raw}`]);
expect(journal().join("\n")).not.toContain("Relevés");
expect(journal().join("\n")).not.toContain("/home/jean");
});
});
// The banner of a refusal asks to refresh the list: « Actualiser », or a new
// folder, reads the folder again and takes the banner away, unless that
// reading fails and puts up its own (#384 review). `browseFolder` sets the
// folder before its scan, so the scan's root files are the new folder's
// (#446 review).
describe("the error banner when the folder is read again (#384)", () => {
const OTHER_FOLDER = "/home/jean/Autres relevés";
/** A refused creation, then the next render of the wizard. */
async function refused() {
ipc.answers.create_sample_import_folders = ["sample_folder_exists:Exemple Desjardins"];
const state = await createSamples();
expect(state.error).toBe("import.empty.sampleErrors.folderExists");
return harness.render(useImportWizard);
}
it("« Actualiser » that goes through takes the banner away", async () => {
const wizard = await refused();
ipc.answers.scan_import_folder.push(SAMPLE_SCAN);
await wizard.refreshFolder();
const state = harness.render(useImportWizard).state;
expect(state.error).toBeNull();
expect(state.errorValues).toBeNull();
expect(state.scannedSources).toBe(SAMPLE_SCAN.sources);
});
it("« Actualiser » that fails puts up its own error instead", async () => {
const wizard = await refused();
ipc.answers.scan_import_folder.push(new Error(`Folder does not exist: ${IMPORT_FOLDER}`));
await wizard.refreshFolder();
const state = harness.render(useImportWizard).state;
expect(state.error).toBe(`Folder does not exist: ${IMPORT_FOLDER}`);
expect(state.errorValues).toBeNull();
});
it("another folder takes the banner away, and shows its own root files", async () => {
const wizard = await refused();
ipc.answers.pick_folder = [{ resolves: OTHER_FOLDER }];
ipc.answers.scan_import_folder.push({ sources: [], root_files: ["releve-4510.csv"] });
await wizard.browseFolder();
const state = harness.render(useImportWizard).state;
expect(state.importFolder).toBe(OTHER_FOLDER);
expect(state.error).toBeNull();
expect(state.errorValues).toBeNull();
expect(state.rootFiles).toEqual(["releve-4510.csv"]);
expect(vi.mocked(invoke)).toHaveBeenCalledWith("scan_import_folder", { folderPath: OTHER_FOLDER });
});
it("a cancelled picker keeps the folder and its banner", async () => {
const wizard = await refused();
ipc.answers.pick_folder = [null];
await wizard.browseFolder();
const state = harness.render(useImportWizard).state;
expect(state.importFolder).toBe(IMPORT_FOLDER);
expect(state.error).toBe("import.empty.sampleErrors.folderExists");
expect(state.errorValues).toEqual({ name: "Exemple Desjardins" });
});
});