/** * Tests for the notifications store and the toast stack: the lifecycle of * a toast, auto-dismiss of info toasts with fake timers, the overflow into * "+n more", ARIA roles, keyboard closing, engine `notification` and * `watchFailed` events (including untrusted fields), and the replay * duplicate guard. */ import { 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 NotificationStack from "../../src/components/notifications/NotificationStack.vue"; import { INFO_TIMEOUT_MS, MAX_KEPT, MAX_VISIBLE, notificationFromEvent, notificationText, useNotificationsStore, } from "../../src/stores/notifications"; /** Pinia of the current test. */ let pinia: Pinia; /** The mounted stack of the current test, unmounted afterwards. */ let wrapper: VueWrapper | null = null; /** Mounts the stack. */ function mountStack(): VueWrapper { wrapper = mount(NotificationStack, { attachTo: document.body, global: { plugins: [pinia] } }); return wrapper; } beforeEach(() => { vi.useFakeTimers(); pinia = createPinia(); setActivePinia(pinia); invoke.mockReset(); listen.mockReset(); invoke.mockResolvedValue(null); }); afterEach(() => { wrapper?.unmount(); wrapper = null; vi.useRealTimers(); }); describe("notifications store", () => { it("shows a toast until it is dismissed", () => { const store = useNotificationsStore(); const id = store.notify({ level: "warning", message: "careful" }); expect(store.toasts).toEqual([{ id, level: "warning", text: "careful" }]); vi.advanceTimersByTime(INFO_TIMEOUT_MS * 10); expect(store.toasts).toHaveLength(1); store.dismiss(id); expect(store.toasts).toEqual([]); }); it("dismisses info toasts after five seconds", () => { const store = useNotificationsStore(); store.notify({ level: "info", message: "saved" }); store.notify({ level: "error", message: "broken" }); vi.advanceTimersByTime(INFO_TIMEOUT_MS - 1); expect(store.toasts).toHaveLength(2); vi.advanceTimersByTime(1); expect(store.toasts.map((toast) => toast.text)).toEqual(["broken"]); }); it("stops the timer of an info toast closed early", () => { const store = useNotificationsStore(); const first = store.notify({ level: "info", message: "a" }); store.dismiss(first); expect(vi.getTimerCount()).toBe(0); }); it("ignores a notification id that is already shown", () => { const store = useNotificationsStore(); store.notify({ id: "n1", level: "warning", message: "a" }); store.notify({ id: "n1", level: "warning", message: "a" }); expect(store.toasts).toHaveLength(1); }); it("collapses older toasts beyond the visible limit", () => { const store = useNotificationsStore(); for (let i = 1; i <= MAX_VISIBLE + 2; i += 1) { store.notify({ level: "error", message: `e${String(i)}` }); } expect(store.visible.map((toast) => toast.text)).toEqual(["e3", "e4", "e5", "e6", "e7"]); expect(store.hiddenCount).toBe(2); store.expand(); expect(store.visible).toHaveLength(MAX_VISIBLE + 2); expect(store.hiddenCount).toBe(0); store.dismiss(store.toasts[0]?.id ?? ""); store.dismiss(store.toasts[0]?.id ?? ""); expect(store.expanded).toBe(false); }); it("keeps at most MAX_KEPT toasts", () => { const store = useNotificationsStore(); for (let i = 0; i < MAX_KEPT + 3; i += 1) { store.notify({ level: "info", message: `i${String(i)}` }); } expect(store.toasts).toHaveLength(MAX_KEPT); expect(store.toasts[0]?.text).toBe("i3"); vi.advanceTimersByTime(INFO_TIMEOUT_MS); expect(store.toasts).toEqual([]); expect(vi.getTimerCount()).toBe(0); }); it("turns a failed command into an error toast", () => { const store = useNotificationsStore(); store.notifyError("theme.systemPreference", { code: "internal", message: "boom" }); expect(store.toasts[0]).toMatchObject({ level: "error", text: "theme.systemPreference failed: boom", }); }); it("dismisses everything", () => { const store = useNotificationsStore(); store.notify({ level: "info", message: "a" }); store.notify({ level: "error", message: "b" }); store.dismissAll(); expect(store.toasts).toEqual([]); expect(vi.getTimerCount()).toBe(0); }); }); describe("notification text", () => { it("uses the catalog message with params", () => { expect( notificationText({ level: "warning", messageKey: "notification.settings.corrupt", message: "english", params: { reason: "bad JSON", backup: "settings.json.bad-1" }, }), ).toBe( "Your settings file could not be read (bad JSON). It was moved to settings.json.bad-1 and the defaults are used.", ); }); it("falls back to the English text, then the key", () => { vi.spyOn(console, "warn").mockImplementation(() => undefined); expect(notificationText({ level: "error", messageKey: "no.such.key", message: "raw" })).toBe("raw"); expect(notificationText({ level: "error", messageKey: "no.such.key" })).toBe("no.such.key"); expect(notificationText({ level: "error" })).toBe(""); }); }); describe("engine events", () => { it("reads notification events and checks untrusted fields", () => { expect( notificationFromEvent({ kind: "notification", id: "n3", level: "warning", messageKey: "notification.recovery.corrupt", message: "Skipped", params: { file: "a.json", reason: "bad", extra: { deep: 1 } }, }), ).toEqual({ id: "n3", level: "warning", messageKey: "notification.recovery.corrupt", message: "Skipped", params: { file: "a.json", reason: "bad", extra: '{"deep":1}' }, }); expect( notificationFromEvent({ kind: "notification", id: 7, level: "loud", params: [1] }), ).toEqual({ id: undefined, level: "error", messageKey: undefined, message: undefined, params: undefined }); }); it("maps watchFailed to a warning", () => { const input = notificationFromEvent({ kind: "watchFailed", message: "too many watches" }); expect(input?.level).toBe("warning"); expect(input && notificationText(input)).toBe( "Lutra stopped watching the project for changes on disk: too many watches", ); }); it("ignores other events", () => { expect(notificationFromEvent({ kind: "projectClosed" })).toBeNull(); }); it("shows engine notifications once started", async () => { const callbacks: ((event: { payload: unknown }) => void)[] = []; const unlisten = vi.fn(); listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => { callbacks.push(callback); return Promise.resolve(unlisten); }); const store = useNotificationsStore(); store.start(); store.start(); await vi.runAllTimersAsync(); expect(listen).toHaveBeenCalledTimes(1); callbacks[0]?.({ payload: { kind: "notification", id: "n1", level: "warning", messageKey: "notification.project.unsavedChanges", params: { path: "/other", what: "a.php" }, }, }); expect(store.toasts[0]?.text).toBe( "Cannot open /other while a.php has unsaved changes. Save or close it first.", ); store.stop(); expect(unlisten).toHaveBeenCalledTimes(1); }); }); describe("NotificationStack", () => { it("renders nothing without toasts", () => { const stack = mountStack(); expect(stack.find('[data-test="toasts"]').exists()).toBe(false); }); it("uses status for info and alert for warnings and errors", async () => { const store = useNotificationsStore(); store.notify({ level: "info", message: "i" }); store.notify({ level: "warning", message: "w" }); store.notify({ level: "error", message: "e" }); const stack = mountStack(); await stack.vm.$nextTick(); const roles = stack.findAll('[data-test="toast"]').map((t) => t.attributes("role")); expect(roles).toEqual(["status", "alert", "alert"]); expect(stack.get('[data-test="toasts"]').attributes("aria-label")).toBe("Notifications"); }); it("closes a toast with its button and with Escape", async () => { const store = useNotificationsStore(); store.notify({ level: "error", message: "one" }); store.notify({ level: "error", message: "two" }); const stack = mountStack(); await stack.vm.$nextTick(); const close = stack.get('[data-test="toast-close"]'); expect(close.attributes("type")).toBe("button"); expect(close.attributes("aria-label")).toBe("Close notification"); await close.trigger("click"); expect(store.toasts.map((t) => t.text)).toEqual(["two"]); await stack.get('[data-test="toast"]').trigger("keydown", { key: "Escape" }); expect(store.toasts).toEqual([]); }); it("collapses older toasts into +n more and expands them", async () => { const store = useNotificationsStore(); for (let i = 1; i <= MAX_VISIBLE + 3; i += 1) { store.notify({ level: "warning", message: `w${String(i)}` }); } const stack = mountStack(); await stack.vm.$nextTick(); expect(stack.findAll('[data-test="toast"]')).toHaveLength(MAX_VISIBLE); const more = stack.get('[data-test="toasts-more"]'); expect(more.text()).toBe("+3 more"); await more.trigger("click"); expect(stack.findAll('[data-test="toast"]')).toHaveLength(MAX_VISIBLE + 3); expect(stack.find('[data-test="toasts-more"]').exists()).toBe(false); }); it("removes an info toast from the screen after five seconds", async () => { const store = useNotificationsStore(); store.notify({ level: "info", message: "done" }); const stack = mountStack(); await stack.vm.$nextTick(); expect(stack.get('[data-test="toast-text"]').text()).toBe("done"); vi.advanceTimersByTime(INFO_TIMEOUT_MS); await stack.vm.$nextTick(); expect(stack.find('[data-test="toast"]').exists()).toBe(false); }); });