/** * Tests of the branches feature (M4.5): reading an untrusted * `git.branches`, the filter, the status-bar label (branch, short hash when * detached, hidden outside a repository), the popup (local before remote, * the current branch marked, filtering, keyboard, choosing the current * branch), checkout with `flushDirty` first, git's refusal as a toast, a * cancelled checkout when a save fails, creating a branch (in the popup and * through `vcs.newBranch {name}`), and the registration of `vcs.branches`, * `vcs.newBranch` and `vcs.checkout`. 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 { useModalsStore } from "../../src/commands/modals"; import { useCommandsStore } from "../../src/commands/store"; import { UI_COMMANDS } from "../../src/commands/uiCommands"; import BranchStatusItem from "../../src/components/vcs/branches/BranchStatusItem.vue"; import { filterBranches, headLabel, toBranches, useBranchesStore, } from "../../src/components/vcs/branches/branches"; import { useChangesStore } 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[]; /** What `git.status` answers. */ let gitStatus: unknown; /** What `git.branches` answers. */ let gitBranches: 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[]; /** * The calls of a command. * * @param command - the command id. */ function callsOf(command: string): Call[] { return calls.filter((c) => c.command === command); } /** Mounts the status-bar item with started stores. */ async function mountItem(): Promise { useChangesStore(pinia).start(); const wrapper = mount(BranchStatusItem, { attachTo: document.body, global: { plugins: [pinia] } }); mounted.push(wrapper); await useCommandsStore(pinia).start(); await flushPromises(); return wrapper; } /** * Opens the popup by clicking the item. * * @param wrapper - the item. */ async function openPopup(wrapper: VueWrapper): Promise { await wrapper.get("[data-test=branch-item]").trigger("click"); await flushPromises(); } /** * The names of the rows of a kind. * * @param wrapper - the item. * @param kind - `local` or `remote`. */ function names(wrapper: VueWrapper, kind: "local" | "remote"): string[] { return wrapper.findAll(`[data-test=branches-${kind}]`).map((row) => row.attributes("data-branch") ?? ""); } beforeEach(() => { pinia = createPinia(); setActivePinia(pinia); calls = []; mounted = []; failures = {}; gitStatus = { available: true, repo: { root: "C:/p", branch: "main", detached: false, head: "0123456789abcdef" }, files: [] }; gitBranches = { current: "main", local: [ { name: "main", head: "0123", upstream: "origin/main" }, { name: "feature/login", head: "4567" }, ], remote: [ { name: "origin/main", head: "0123" }, { name: "origin/release", head: "89ab" }, ], }; saveAll = { saved: [], failed: [], skipped: [] }; Element.prototype.scrollIntoView = () => undefined; invoke.mockReset(); listen.mockReset(); listen.mockImplementation(() => Promise.resolve(() => undefined)); 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 }, { id: "git.branches", label: "Git Branches", 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.branches": return Promise.resolve(gitBranches); case "file.saveAll": return Promise.resolve(saveAll); default: return Promise.resolve({}); } }); }); afterEach(() => { for (const wrapper of mounted) { wrapper.unmount(); } useChangesStore(pinia).stop(); document.body.innerHTML = ""; }); describe("reading git.branches", () => { it("drops malformed entries and sorts by name", () => { const list = toBranches({ current: "", local: [{ name: "z", head: "1" }, { name: "" }, "x", null, { name: "a", head: 5, upstream: "origin/a" }], remote: "nope", }); expect(list).toEqual({ current: null, local: [ { name: "a", head: "", upstream: "origin/a" }, { name: "z", head: "1" }, ], remote: [], }); expect(toBranches(null)).toBeNull(); expect(toBranches([1])).toBeNull(); }); it("filters by every word, ignoring case", () => { const all = [{ name: "feature/Login", head: "" }, { name: "main", head: "" }, { name: "fix/login-form", head: "" }]; expect(filterBranches(all, "LOGIN").map((b) => b.name)).toEqual(["feature/Login", "fix/login-form"]); expect(filterBranches(all, "login fix").map((b) => b.name)).toEqual(["fix/login-form"]); expect(filterBranches(all, " ")).toHaveLength(3); }); it("labels HEAD with the branch or the short hash", () => { expect(headLabel({ root: "/r", branch: "main", detached: false, head: "abc" })).toBe("main"); expect(headLabel({ root: "/r", detached: true, head: "0123456789" })).toBe("0123456"); expect(headLabel({ root: "/r", branch: "main", detached: false })).toBe("main"); expect(headLabel({ root: "/r", detached: false })).toBeNull(); expect(headLabel(null)).toBeNull(); }); }); describe("the status-bar item", () => { it("shows the branch, the short hash when detached, and hides outside a repository", async () => { const wrapper = await mountItem(); expect(wrapper.get("[data-test=branch-item]").text()).toBe("main"); expect(wrapper.get("[data-test=branch-item]").attributes("aria-label")).toContain("main"); gitStatus = { available: true, repo: { root: "C:/p", detached: true, head: "fedcba9876" }, files: [] }; await useChangesStore(pinia).refresh(); expect(wrapper.get("[data-test=branch-item]").text()).toBe("fedcba9"); expect(wrapper.get("[data-test=branch-item]").attributes("aria-label")).toContain("Detached"); gitStatus = { available: true, repo: null, files: [] }; await useChangesStore(pinia).refresh(); expect(wrapper.find("[data-test=branch-item]").exists()).toBe(false); gitStatus = { available: false, error: "no git", repo: null, files: [] }; await useChangesStore(pinia).refresh(); expect(wrapper.find("[data-test=branch-item]").exists()).toBe(false); }); }); describe("the branches popup", () => { it("lists local before remote branches, marks the current one and filters", async () => { const wrapper = await mountItem(); await openPopup(wrapper); expect(callsOf("git.branches")[0]?.via).toBe("engine_execute_waiting"); expect(names(wrapper, "local")).toEqual(["feature/login", "main"]); expect(names(wrapper, "remote")).toEqual(["origin/main", "origin/release"]); const main = wrapper.findAll("[data-test=branches-local]")[1]; expect(main?.attributes("aria-current")).toBe("true"); expect(main?.text()).toContain("current"); expect(document.activeElement).toBe(wrapper.get("[data-test=branches-filter]").element); expect(useModalsStore(pinia).current).toBe("branches"); await wrapper.get("[data-test=branches-filter]").setValue("rel"); expect(names(wrapper, "local")).toEqual([]); expect(names(wrapper, "remote")).toEqual(["origin/release"]); await wrapper.get("[data-test=branches-filter]").setValue("zzz"); expect(wrapper.get("[data-test=branches-hint]").text()).toBe("No branch matches"); }); it("checks out with Enter after saving dirty buffers", async () => { const wrapper = await mountItem(); await openPopup(wrapper); const filter = wrapper.get("[data-test=branches-filter]"); await filter.setValue("login"); await filter.trigger("keydown", { key: "Enter" }); await flushPromises(); const order = calls.map((c) => c.command).filter((c) => c === "file.saveAll" || c === "git.checkout"); expect(order).toEqual(["file.saveAll", "git.checkout"]); expect(callsOf("git.checkout")[0]).toMatchObject({ via: "engine_execute_waiting", params: { branch: "feature/login" } }); expect(wrapper.find("[data-test=branches]").exists()).toBe(false); expect(useModalsStore(pinia).current).toBeNull(); expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toBe("Checked out feature/login"); }); it("checks out a remote branch from a click and only closes on the current branch", async () => { const wrapper = await mountItem(); await openPopup(wrapper); await wrapper.findAll("[data-test=branches-local]")[1]?.trigger("click"); await flushPromises(); expect(callsOf("git.checkout")).toHaveLength(0); expect(wrapper.find("[data-test=branches]").exists()).toBe(false); await openPopup(wrapper); await wrapper.findAll("[data-test=branches-remote]")[1]?.trigger("click"); await flushPromises(); expect(callsOf("git.checkout")[0]?.params).toEqual({ branch: "origin/release" }); }); it("moves with the arrow keys and closes with Escape", async () => { const wrapper = await mountItem(); await openPopup(wrapper); const branches = useBranchesStore(pinia); expect(branches.selected).toBe(1); const filter = wrapper.get("[data-test=branches-filter]"); await filter.trigger("keydown", { key: "ArrowUp" }); expect(branches.selected).toBe(0); await filter.trigger("keydown", { key: "ArrowUp" }); expect(branches.selected).toBe(0); await filter.trigger("keydown", { key: "PageDown" }); expect(branches.selected).toBe(4); await filter.trigger("keydown", { key: "Escape" }); await flushPromises(); expect(wrapper.find("[data-test=branches]").exists()).toBe(false); }); it("toasts git's refusal and names the branch", async () => { failures["git.checkout"] = { code: "failed", message: "error: Your local changes to the following files would be overwritten by checkout:\n\tsrc/a.php", }; const wrapper = await mountItem(); await openPopup(wrapper); await wrapper.findAll("[data-test=branches-local]")[0]?.trigger("click"); await flushPromises(); const toast = useNotificationsStore(pinia).toasts.at(-1); expect(toast?.level).toBe("error"); expect(toast?.text).toContain("Git did not check out feature/login"); expect(toast?.text).toContain("would be overwritten by checkout"); expect(useBranchesStore(pinia).busy).toBe(false); }); it("cancels the checkout when a buffer cannot be saved", async () => { saveAll = { saved: [], failed: [{ id: 3, path: "src/a.php", message: "disk full" }], skipped: [] }; const wrapper = await mountItem(); await openPopup(wrapper); await wrapper.findAll("[data-test=branches-local]")[0]?.trigger("click"); await flushPromises(); expect(callsOf("git.checkout")).toHaveLength(0); const toast = useNotificationsStore(pinia).toasts.find((t) => t.text.includes("Checkout of feature/login cancelled")); expect(toast?.level).toBe("warning"); }); it("creates a branch from the popup and keeps git's refusal in place", async () => { const wrapper = await mountItem(); await openPopup(wrapper); await wrapper.get("[data-test=branches-filter]").setValue("topic"); await wrapper.get("[data-test=branches-new]").trigger("click"); await flushPromises(); const name = wrapper.get("[data-test=branches-new-name]"); expect((name.element as HTMLInputElement).value).toBe("topic"); expect(document.activeElement).toBe(name.element); await name.setValue(" "); await wrapper.get("[data-test=branches-new-form]").trigger("submit"); await flushPromises(); expect(wrapper.get("[data-test=branches-new-error]").text()).toBe("Enter a name for the branch."); expect(callsOf("git.createBranch")).toHaveLength(0); failures["git.createBranch"] = { code: "failed", message: "fatal: a branch named 'main' already exists" }; await name.setValue("main"); await wrapper.get("[data-test=branches-new-form]").trigger("submit"); await flushPromises(); expect(wrapper.get("[data-test=branches-new-error]").text()).toContain("already exists"); expect(wrapper.find("[data-test=branches]").exists()).toBe(true); delete failures["git.createBranch"]; await name.setValue("topic/x"); await wrapper.get("[data-test=branches-new-checkout]").setValue(false); await wrapper.get("[data-test=branches-new-form]").trigger("submit"); await flushPromises(); expect(callsOf("git.createBranch").at(-1)).toMatchObject({ via: "engine_execute_waiting", params: { name: "topic/x", checkout: false }, }); expect(wrapper.find("[data-test=branches]").exists()).toBe(false); expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toBe("Created branch topic/x"); }); it("goes back from the new branch's name to the list with Escape", async () => { const wrapper = await mountItem(); await useCommandsStore(pinia).execute("vcs.newBranch"); await flushPromises(); expect(wrapper.find("[data-test=branches-new-form]").exists()).toBe(true); await wrapper.get("[data-test=branches-new-name]").trigger("keydown", { key: "Escape" }); await flushPromises(); expect(wrapper.find("[data-test=branches-filter]").exists()).toBe(true); }); }); describe("the branch commands", () => { it("are registered with menu paths and without shortcuts", () => { const byId = new Map(UI_COMMANDS.map((c) => [c.id, c])); expect(byId.get("vcs.branches")).toMatchObject({ menuPath: "Git/Branches…" }); expect(byId.get("vcs.newBranch")).toMatchObject({ menuPath: "Git/New Branch…" }); expect(byId.get("vcs.checkout")?.menuPath).toBeUndefined(); expect(["vcs.branches", "vcs.newBranch", "vcs.checkout"].map((id) => byId.get(id)?.defaultShortcut)).toEqual([ undefined, undefined, undefined, ]); }); it("vcs.checkout {branch} saves first, opens the popup without a branch and refuses a bad one", async () => { const wrapper = await mountItem(); const commands = useCommandsStore(pinia); await commands.execute("vcs.checkout", { branch: "feature/login" }); await flushPromises(); expect(callsOf("file.saveAll")).toHaveLength(1); expect(callsOf("git.checkout")[0]?.params).toEqual({ branch: "feature/login" }); await commands.execute("vcs.checkout", { branch: 3 }); await flushPromises(); expect(callsOf("git.checkout")).toHaveLength(1); expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toContain("vcs.checkout needs a branch name"); await commands.execute("vcs.checkout"); await flushPromises(); expect(wrapper.find("[data-test=branches-filter]").exists()).toBe(true); }); it("vcs.newBranch {name} creates and checks out without the popup", async () => { const wrapper = await mountItem(); const commands = useCommandsStore(pinia); await commands.execute("vcs.newBranch", { name: "agent/work" }); await flushPromises(); expect(callsOf("git.createBranch")[0]?.params).toEqual({ name: "agent/work", checkout: true }); expect(wrapper.find("[data-test=branches]").exists()).toBe(false); failures["git.createBranch"] = { code: "invalid_params", message: "invalid branch name: -x" }; await commands.execute("vcs.newBranch", { name: "-x", checkout: false }); await flushPromises(); const toast = useNotificationsStore(pinia).toasts.at(-1); expect(toast?.level).toBe("error"); expect(toast?.text).toContain("Branch -x was not created: invalid branch name: -x"); }); it("are disabled without a project", async () => { invoke.mockImplementation((cmd: string) => Promise.resolve(cmd === "engine_list_commands" ? [{ id: "git.branches", label: "", enabled: false }] : null), ); await mountItem(); const commands = useCommandsStore(pinia); expect(commands.isEnabled("vcs.branches")).toBe(false); expect(commands.isEnabled("vcs.newBranch")).toBe(false); expect(commands.isEnabled("vcs.checkout")).toBe(false); }); });