desktopTray.test.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import type { MenuItemConstructorOptions } from "electron";
  2. import { DesktopCommandIds, type Locale } from "@zcode/shared";
  3. import { beforeEach, describe, expect, it, vi } from "vitest";
  4. const captured = vi.hoisted(() => ({
  5. template: [] as MenuItemConstructorOptions[],
  6. }));
  7. vi.mock("electron", () => ({
  8. app: { isPackaged: false },
  9. Menu: {
  10. buildFromTemplate: (template: MenuItemConstructorOptions[]) => {
  11. captured.template = template;
  12. return { template };
  13. },
  14. },
  15. Tray: class {
  16. setToolTip() {}
  17. setContextMenu() {}
  18. on() {}
  19. },
  20. }));
  21. describe("desktop tray log export", () => {
  22. beforeEach(() => {
  23. vi.resetModules();
  24. captured.template = [];
  25. });
  26. it.each(["win32", "linux"] as const)(
  27. "%s replaces data deletion with localized log export and waits for the window",
  28. async (platform) => {
  29. const { createDesktopTray, updateWindowsDesktopTrayMenu } =
  30. await import("@desktop/main/desktopTray.js");
  31. let locale: Locale = "zh-CN";
  32. const windowReady = Promise.withResolvers<void>();
  33. const showCurrentWindow = vi.fn(() => windowReady.promise);
  34. const executeDesktopCommand = vi.fn(async () => undefined);
  35. createDesktopTray({
  36. platform,
  37. getLocale: () => locale,
  38. showCurrentWindow,
  39. executeDesktopCommand,
  40. quitApp: vi.fn(),
  41. logger: { warn: vi.fn() },
  42. });
  43. const labels = () => captured.template.map((item) => item.label).filter(Boolean);
  44. expect(labels()).not.toContain("清除所有数据");
  45. expect(labels().slice(-3)).toEqual(["关于 ZCode", "导出日志", "退出"]);
  46. locale = "en-US";
  47. updateWindowsDesktopTrayMenu();
  48. expect(labels()).not.toContain("Clear all data");
  49. expect(labels().slice(-3)).toEqual(["About ZCode", "Export logs", "Quit"]);
  50. const item = captured.template.find((entry) => entry.label === "Export logs");
  51. expect(item?.click).toBeDefined();
  52. // 模板回调不读取 Electron 事件参数;直接触发同一个原生菜单动作。
  53. (item!.click as () => void)();
  54. expect(showCurrentWindow).toHaveBeenCalledExactlyOnceWith();
  55. expect(executeDesktopCommand).not.toHaveBeenCalled();
  56. windowReady.resolve();
  57. await vi.waitFor(() =>
  58. expect(executeDesktopCommand).toHaveBeenCalledExactlyOnceWith(DesktopCommandIds.ExportLogs),
  59. );
  60. },
  61. );
  62. });