notificationEnabledBroadcast.test.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // @vitest-environment jsdom
  2. import { beforeEach, describe, expect, it, vi } from "vitest";
  3. import type { IBroadcastService } from "@zcode/services";
  4. import { createZCodeStore } from "@/store/index.js";
  5. function createBroadcastFixture() {
  6. let receive: Parameters<IBroadcastService["onMessage"]>[0] | undefined;
  7. const send = vi.fn(async () => {});
  8. const service: IBroadcastService = {
  9. send,
  10. acquireClaim: async () => ({ status: "unavailable" }),
  11. commitClaim: async () => {},
  12. releaseClaim: async () => {},
  13. tryClaim: async () => false,
  14. onMessage: (listener) => {
  15. receive = listener;
  16. return { dispose: () => {} };
  17. },
  18. };
  19. return { send, service, receive: () => receive };
  20. }
  21. describe("任务通知开关跨窗口同步", () => {
  22. beforeEach(() => localStorage.clear());
  23. it("切换开关广播 state:notificationEnabled,其他窗口按广播应用且不回播", () => {
  24. const { send, service, receive } = createBroadcastFixture();
  25. const store = createZCodeStore(service);
  26. expect(store.getState().notificationEnabled).toBe(true);
  27. // 窗口 A 关闭通知:本地生效并广播
  28. store.getState().setNotificationEnabled(false);
  29. expect(store.getState().notificationEnabled).toBe(false);
  30. expect(send).toHaveBeenCalledWith({ channel: "state:notificationEnabled", payload: false });
  31. send.mockClear();
  32. // 模拟窗口 B 收到广播:应用开关(含 localStorage 持久化),不回播
  33. receive()?.({ channel: "state:notificationEnabled", payload: false });
  34. expect(store.getState().notificationEnabled).toBe(false);
  35. expect(localStorage.getItem("zcode-notification-enabled")).toBe("false");
  36. expect(send).not.toHaveBeenCalled();
  37. // 非法 payload 不改变状态
  38. receive()?.({ channel: "state:notificationEnabled", payload: "unexpected" });
  39. expect(store.getState().notificationEnabled).toBe(false);
  40. });
  41. it("新窗口启动从 localStorage 读最新开关值(跨窗口共享持久层)", () => {
  42. localStorage.setItem("zcode-notification-enabled", "false");
  43. const { service } = createBroadcastFixture();
  44. const store = createZCodeStore(service);
  45. expect(store.getState().notificationEnabled).toBe(false);
  46. });
  47. });