/** * Tests of the Changes tool window (M4.2): the store (reading an untrusted * `git.status`, grouping into Staged / Changes / Untracked, refresh on * start, project open and `gitChanged`, serialised refreshes, staging and * unstaging per file and per group, renames, commit with `flushDirty` * first, a cancelled commit when a save fails, git's error as a toast), * the window (status line, hints, checkboxes, keyboard, double-click * through `vcs.showDiff` or `file.open`), and the commands `vcs.openChanges`, * `vcs.commit` and `vcs.refresh` in the main layout. The engine is a fake * behind the mocked Tauri `invoke` and `listen`. */ import { flushPromises, mount, type VueWrapper } from "@vue/test-utils"; import { createPinia, setActivePinia, type Pinia } from "pinia"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const invoke = vi.hoisted(() => vi.fn()); const listen = vi.hoisted(() => vi.fn()); vi.mock("@tauri-apps/api/core", () => ({ invoke })); vi.mock("@tauri-apps/api/event", () => ({ listen })); import { useCommandsStore } from "../../src/commands/store"; import MainLayout from "../../src/components/layout/MainLayout.vue"; import ChangesToolWindow from "../../src/components/vcs/changes/ChangesToolWindow.vue"; import { groupFiles, toStatus, unstagePaths, useChangesStore, type ChangedFile, } from "../../src/components/vcs/changes/changes"; import { useNotificationsStore } from "../../src/stores/notifications"; /** A recorded engine call. */ interface Call { /** `engine_execute` or `engine_execute_waiting`. */ via: string; /** Command id. */ command: string; /** Its params. */ params: Record; } /** Every engine call, in order. */ let calls: Call[]; /** Engine event callbacks of every subscription. */ let listeners: ((event: { payload: unknown }) => void)[]; /** What `git.status` answers. */ let gitStatus: unknown; /** Errors to throw, by command id. */ let failures: Record; /** What `file.saveAll` answers. */ let saveAll: unknown; /** Pinia of the current test. */ let pinia: Pinia; /** Mounted components, unmounted after each test. */ let mounted: VueWrapper[]; /** * Sends an engine event to every subscription. * * @param payload - the event. */ async function emit(payload: unknown): Promise { for (const listener of [...listeners]) { listener({ payload }); } await flushPromises(); } /** * The calls of a command. * * @param command - the command id. */ function callsOf(command: string): Call[] { return calls.filter((c) => c.command === command); } /** A status with a staged, a partly staged, a changed, a renamed and an untracked file. */ function sampleStatus(): Record { return { available: true, repo: { root: "C:/p", branch: "main", detached: false, head: "0123456789abcdef" }, files: [ { path: "src/b.php", index: "modified", worktree: "unmodified" }, { path: "src/a.php", index: "modified", worktree: "modified" }, { path: "c.php", index: "unmodified", worktree: "deleted" }, { path: "new/name.php", origPath: "old/name.php", index: "renamed", worktree: "unmodified" }, { path: "tmp.txt", index: "untracked", worktree: "untracked" }, ], }; } /** Mounts the window with a started store. */ async function mountChanges(): Promise { useChangesStore(pinia).start(); const wrapper = mount(ChangesToolWindow, { attachTo: document.body, global: { plugins: [pinia] } }); mounted.push(wrapper); await flushPromises(); return wrapper; } /** * The text of every row. * * @param wrapper - the window. */ function rowTexts(wrapper: VueWrapper): string[] { return wrapper.findAll("[data-test=changes-row]").map((row) => row.text()); } beforeEach(() => { pinia = createPinia(); setActivePinia(pinia); calls = []; listeners = []; mounted = []; failures = {}; gitStatus = sampleStatus(); saveAll = { saved: [], failed: [], skipped: [] }; Element.prototype.scrollIntoView = () => undefined; invoke.mockReset(); listen.mockReset(); listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => { listeners.push(callback); return Promise.resolve(() => { listeners = listeners.filter((l) => l !== callback); }); }); invoke.mockImplementation((cmd: string, args?: { command: string; params: Record }) => { if (cmd === "engine_list_commands") { return Promise.resolve([{ id: "git.status", label: "Git Status", enabled: true }]); } if ((cmd !== "engine_execute" && cmd !== "engine_execute_waiting") || !args) { return Promise.resolve(null); } calls.push({ via: cmd, command: args.command, params: args.params }); const failure = failures[args.command]; if (failure) { return Promise.reject(Object.assign(new Error(failure.message), failure)); } switch (args.command) { case "git.status": return Promise.resolve(gitStatus); case "git.commit": return Promise.resolve({ commit: "fedcba9876543210", summary: String(args.params.message).split("\n")[0] }); case "file.saveAll": return Promise.resolve(saveAll); case "file.open": return Promise.resolve({ id: 1, path: args.params.path, text: "", version: 0 }); default: return Promise.resolve({}); } }); }); afterEach(() => { for (const wrapper of mounted) { wrapper.unmount(); } useChangesStore(pinia).stop(); document.body.innerHTML = ""; }); describe("reading git.status", () => { it("drops malformed entries, keeps renames and sorts by path", () => { const status = toStatus({ available: true, repo: { root: "/r", detached: true, head: "abc" }, files: [ { path: "z.php", index: "modified", worktree: "unmodified" }, { path: "", index: "modified", worktree: "unmodified" }, { path: "x.php", index: "weird", worktree: "unmodified" }, "nope", null, { path: "a.php", origPath: "b.php", index: "renamed", worktree: "modified" }, ], }); expect(status?.files.map((f) => f.path)).toEqual(["a.php", "z.php"]); expect(status?.files[0]?.origPath).toBe("b.php"); expect(status?.repo).toEqual({ root: "/r", detached: true, head: "abc" }); expect(toStatus(null)).toBeNull(); expect(toStatus([1, 2])).toBeNull(); expect(toStatus({ available: false, error: "git not found", repo: null, files: "x" })).toEqual({ available: false, error: "git not found", repo: null, files: [], }); }); it("groups files: partly staged in both, conflicts in Changes, untracked apart", () => { const files: ChangedFile[] = [ { path: "a", index: "modified", worktree: "modified" }, { path: "b", index: "added", worktree: "unmodified" }, { path: "c", index: "unmodified", worktree: "deleted" }, { path: "d", index: "conflicted", worktree: "conflicted" }, { path: "e", index: "untracked", worktree: "untracked" }, ]; const groups = groupFiles(files); expect(groups.staged.map((r) => `${r.file.path}:${r.state}`)).toEqual(["a:modified", "b:added"]); expect(groups.changes.map((r) => `${r.file.path}:${r.state}`)).toEqual(["a:modified", "c:deleted", "d:conflicted"]); expect(groups.untracked.map((r) => r.file.path)).toEqual(["e"]); }); it("unstages a staged rename with both paths", () => { const groups = groupFiles([ { path: "new.php", origPath: "old.php", index: "renamed", worktree: "unmodified" }, { path: "x.php", index: "modified", worktree: "unmodified" }, ]); expect(unstagePaths(groups.staged)).toEqual(["new.php", "old.php", "x.php"]); }); }); describe("the Changes store", () => { it("reads the status through runWaiting on start, project open and gitChanged", async () => { const changes = useChangesStore(pinia); changes.start(); await flushPromises(); expect(callsOf("git.status")).toHaveLength(1); expect(callsOf("git.status")[0]?.via).toBe("engine_execute_waiting"); expect(changes.groups.staged.map((r) => r.file.path)).toEqual(["new/name.php", "src/a.php", "src/b.php"]); await emit({ kind: "gitChanged", available: true, repo: null, filesChanged: true }); await emit({ kind: "projectOpened", root: "C:/p", name: "p" }); expect(callsOf("git.status")).toHaveLength(3); await emit({ kind: "projectClosed" }); expect(changes.status).toBeNull(); expect(changes.rows).toHaveLength(0); }); it("serialises refreshes: calls during a round cause one more round", async () => { const changes = useChangesStore(pinia); const first = changes.refresh(); void changes.refresh(); void changes.refresh(); await first; await flushPromises(); expect(callsOf("git.status")).toHaveLength(2); }); it("stages and unstages per file and per group, then re-reads", async () => { const changes = useChangesStore(pinia); await changes.refresh(); const untracked = changes.groups.untracked[0]; if (!untracked) throw new Error("no untracked row"); await changes.toggle(untracked); expect(callsOf("git.stage").map((c) => c.params)).toEqual([{ paths: ["tmp.txt"] }]); await changes.toggleGroup("changes"); expect(callsOf("git.stage")[1]?.params).toEqual({ paths: ["c.php", "src/a.php"] }); await changes.toggleGroup("staged"); expect(callsOf("git.unstage")[0]?.params).toEqual({ paths: ["new/name.php", "old/name.php", "src/a.php", "src/b.php"], }); expect(callsOf("git.stage")[0]?.via).toBe("engine_execute_waiting"); expect(callsOf("git.status")).toHaveLength(4); }); it("toasts git's message when staging fails", async () => { const changes = useChangesStore(pinia); await changes.refresh(); failures["git.stage"] = { code: "failed", message: "fatal: index.lock exists" }; await changes.toggleGroup("untracked"); const toasts = useNotificationsStore(pinia).toasts; expect(toasts.at(-1)?.level).toBe("error"); expect(toasts.at(-1)?.text).toContain("fatal: index.lock exists"); expect(changes.busy).toBe(false); }); it("saves dirty buffers before committing and toasts the short hash", async () => { const changes = useChangesStore(pinia); await changes.refresh(); changes.message = "Fix the parser\n\nDetails"; expect(changes.canCommit).toBe(true); const hash = await changes.commit(); expect(hash).toBe("fedcba9876543210"); const order = calls.map((c) => c.command).filter((c) => c === "file.saveAll" || c === "git.commit"); expect(order).toEqual(["file.saveAll", "git.commit"]); expect(callsOf("git.commit")[0]?.params).toEqual({ message: "Fix the parser\n\nDetails", amend: false }); expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toBe("Committed fedcba9: Fix the parser"); expect(changes.message).toBe(""); }); it("cancels the commit when a buffer cannot be saved", async () => { const changes = useChangesStore(pinia); await changes.refresh(); saveAll = { saved: [], failed: [{ id: 3, path: "src/a.php", message: "disk full" }], skipped: [] }; changes.message = "msg"; expect(await changes.commit()).toBeNull(); expect(callsOf("git.commit")).toHaveLength(0); expect(useNotificationsStore(pinia).toasts.some((t) => t.text.includes("Commit cancelled"))).toBe(true); expect(changes.message).toBe("msg"); }); it("refuses an empty message and an empty commit, but allows an amend without staged files", async () => { gitStatus = { ...sampleStatus(), files: [{ path: "a.php", index: "unmodified", worktree: "modified" }] }; const changes = useChangesStore(pinia); await changes.refresh(); changes.message = " "; expect(changes.canCommit).toBe(false); changes.message = "reword"; expect(changes.canCommit).toBe(false); changes.amend = true; expect(changes.canCommit).toBe(true); await changes.commit(); expect(callsOf("git.commit")[0]?.params).toEqual({ message: "reword", amend: true }); expect(changes.amend).toBe(false); }); it("keeps the message when git refuses the commit", async () => { const changes = useChangesStore(pinia); await changes.refresh(); failures["git.commit"] = { code: "failed", message: "pre-commit hook failed: lint" }; changes.message = "keep me"; expect(await changes.commit()).toBeNull(); expect(changes.message).toBe("keep me"); expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toContain("pre-commit hook failed: lint"); }); }); describe("the Changes window", () => { it("shows the branch, the counts and the three groups", async () => { const wrapper = await mountChanges(); expect(wrapper.get("[data-test=changes-status]").text()).toBe("main: 3 staged, 2 changed, 1 untracked"); expect(wrapper.find("[data-test=changes-group-staged]").exists()).toBe(true); expect(wrapper.find("[data-test=changes-group-changes]").exists()).toBe(true); expect(wrapper.find("[data-test=changes-group-untracked]").exists()).toBe(true); expect(rowTexts(wrapper)[0]).toContain("name.php"); expect(rowTexts(wrapper)[0]).toContain("from old/name.php"); }); it("explains a missing git, a folder without a repository and a clean tree", async () => { gitStatus = { available: false, error: "git 2.20 is older than 2.30", repo: null, files: [] }; const wrapper = await mountChanges(); expect(wrapper.get("[data-test=changes-status]").text()).toContain("git 2.20 is older than 2.30"); expect(wrapper.find("[data-test=changes-hint]").exists()).toBe(true); gitStatus = { available: true, repo: null, files: [] }; await useChangesStore(pinia).refresh(); expect(wrapper.get("[data-test=changes-status]").text()).toBe("This project is not in a Git repository"); gitStatus = { available: true, repo: { root: "/r", detached: true, head: "abcdef0123456" }, files: [] }; await useChangesStore(pinia).refresh(); expect(wrapper.get("[data-test=changes-status]").text()).toBe("abcdef0: no changes"); expect(wrapper.get("[data-test=changes-message]").attributes("disabled")).toBeUndefined(); }); it("stages and unstages through the checkboxes", async () => { const wrapper = await mountChanges(); await wrapper.get("[data-test=changes-group-toggle-untracked]").trigger("click"); await flushPromises(); expect(callsOf("git.stage")[0]?.params).toEqual({ paths: ["tmp.txt"] }); const firstToggle = wrapper.findAll("[data-test=changes-row-toggle]")[0]; await firstToggle?.trigger("click"); await flushPromises(); expect(callsOf("git.unstage")[0]?.params).toEqual({ paths: ["new/name.php", "old/name.php"] }); }); it("moves with the arrow keys, toggles with Space and opens with Enter", async () => { const wrapper = await mountChanges(); const list = wrapper.get("[data-test=changes-list]"); await list.trigger("keydown", { key: "End" }); expect(useChangesStore(pinia).selectedKey).toBe("untracked:tmp.txt"); await list.trigger("keydown", { key: " " }); await flushPromises(); expect(callsOf("git.stage")[0]?.params).toEqual({ paths: ["tmp.txt"] }); await list.trigger("keydown", { key: "ArrowUp" }); await list.trigger("keydown", { key: "Enter" }); await flushPromises(); expect(callsOf("file.open").map((c) => c.params)).toEqual([{ path: "src/a.php" }]); }); it("opens through vcs.showDiff when it is provided, and never opens a deleted file", async () => { const wrapper = await mountChanges(); const rows = wrapper.findAll("[data-test=changes-row]"); const deleted = rows.find((row) => row.text().includes("c.php")); await deleted?.trigger("dblclick"); await flushPromises(); expect(callsOf("file.open")).toHaveLength(0); const diffs: unknown[] = []; useCommandsStore(pinia).provide("vcs.showDiff", { run: (params) => void diffs.push(params) }); await rows[0]?.trigger("dblclick"); await flushPromises(); expect(diffs).toEqual([{ path: "new/name.php", staged: true }]); expect(callsOf("file.open")).toHaveLength(0); }); it("commits from the button and with Ctrl+Enter in the box", async () => { const wrapper = await mountChanges(); const button = wrapper.get("[data-test=changes-commit-button]"); expect(button.attributes("disabled")).toBeDefined(); await wrapper.get("[data-test=changes-message]").setValue("First"); expect(button.attributes("disabled")).toBeUndefined(); await wrapper.get("[data-test=changes-commit]").trigger("submit"); await flushPromises(); expect(callsOf("git.commit")).toHaveLength(1); await wrapper.get("[data-test=changes-message]").setValue("Second"); await wrapper.get("[data-test=changes-amend]").setValue(true); expect(button.text()).toBe("Amend Commit"); await wrapper.get("[data-test=changes-message]").trigger("keydown", { key: "Enter", ctrlKey: true }); await flushPromises(); expect(callsOf("git.commit")[1]?.params).toEqual({ message: "Second", amend: true }); }); }); describe("the vcs commands in the main layout", () => { /** Mounts the layout and starts the commands store. */ async function mountLayout(): Promise { const wrapper = mount(MainLayout, { attachTo: document.body, global: { plugins: [pinia], stubs: { ProjectToolWindow: true, StatusBar: true } }, }); mounted.push(wrapper); await useCommandsStore(pinia).start(); await flushPromises(); return wrapper; } it("registers the commands with menu paths and shortcuts", async () => { await mountLayout(); const registered = callsOf("ui.registerCommands")[0]?.params.commands as { id: string; defaultShortcut?: string; menuPath?: string; }[]; expect(registered.find((c) => c.id === "vcs.openChanges")).toMatchObject({ defaultShortcut: "Mod+Alt+G", menuPath: "Git/Changes" }); expect(registered.find((c) => c.id === "vcs.commit")).toMatchObject({ defaultShortcut: "Mod+K", menuPath: "Git/Commit…" }); expect(registered.find((c) => c.id === "vcs.refresh")?.menuPath).toBe("Git/Refresh Changes"); }); it("opens the tab with its shortcut, focuses the box with vcs.commit and refreshes", async () => { const wrapper = await mountLayout(); expect(wrapper.find("[data-test=changes]").exists()).toBe(false); window.dispatchEvent(new KeyboardEvent("keydown", { key: "g", code: "KeyG", ctrlKey: true, altKey: true, bubbles: true })); await flushPromises(); expect(wrapper.get("[data-test=changes]").isVisible()).toBe(true); const commands = useCommandsStore(pinia); await commands.execute("vcs.commit"); await flushPromises(); expect(document.activeElement).toBe(wrapper.get("[data-test=changes-message]").element); const before = callsOf("git.status").length; await commands.execute("vcs.refresh"); await flushPromises(); expect(callsOf("git.status").length).toBe(before + 1); await commands.execute("problems.open"); await flushPromises(); expect(wrapper.findAll("[data-test=bottom-panel] [role=tab]").length).toBeGreaterThanOrEqual(2); }); });