GlobalNoticeSurface.test.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // @vitest-environment jsdom
  2. import { createElement } from "react";
  3. import { act, cleanup, render } from "@testing-library/react";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import {
  6. createGlobalNoticeStore,
  7. type GlobalNoticeStorage,
  8. } from "@/global-notice/globalNoticeStore.js";
  9. import { GlobalNoticeSurface } from "@/global-notice/GlobalNoticeSurface.js";
  10. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  11. function memoryStorage(): GlobalNoticeStorage {
  12. const values = new Map<string, string>();
  13. return {
  14. getItem: (key) => values.get(key) ?? null,
  15. setItem: (key, value) => values.set(key, value),
  16. removeItem: (key) => values.delete(key),
  17. };
  18. }
  19. afterEach(() => {
  20. cleanup();
  21. vi.useRealTimers();
  22. vi.clearAllMocks();
  23. Object.defineProperty(navigator, "clipboard", {
  24. configurable: true,
  25. value: undefined,
  26. });
  27. });
  28. function publishShareNotice(
  29. store: ReturnType<typeof createGlobalNoticeStore>,
  30. now = Date.now(),
  31. ): void {
  32. store.publish({
  33. noticeId: "notice-1",
  34. dedupeKey: "highspeed-share:latest",
  35. type: "highspeed-share",
  36. schemaVersion: 1,
  37. scope: "user",
  38. priority: "normal",
  39. interruptPolicy: "passive",
  40. createdAt: now,
  41. expiresAt: now + 1000,
  42. payload: {
  43. cardId: "hsc-1",
  44. shareId: "share-1",
  45. shareUrl: "https://example.test/share-1",
  46. shareExpiresAt: now + 10_000,
  47. tokenUsage: 10,
  48. durationSeconds: 1,
  49. },
  50. actions: [],
  51. dismissPolicy: { kind: "cooldown", cooldownMs: 24 * 60 * 60_000 },
  52. persistencePolicy: "latest-only",
  53. source: "highspeed",
  54. revision: 1,
  55. });
  56. }
  57. describe("GlobalNoticeSurface", () => {
  58. it("hides a visible notice when its expiry is reached without another store event", () => {
  59. vi.useFakeTimers();
  60. vi.setSystemTime(1000);
  61. const store = createGlobalNoticeStore({ storage: memoryStorage() });
  62. publishShareNotice(store, 1000);
  63. const { container } = render(
  64. createElement(
  65. ZCodeIntlProvider,
  66. { initialLocale: "zh-CN" },
  67. createElement(GlobalNoticeSurface, { store }),
  68. ),
  69. );
  70. expect(container.querySelector('[data-global-notice-type="highspeed-share"]')).not.toBeNull();
  71. act(() => {
  72. vi.advanceTimersByTime(1020);
  73. });
  74. expect(container.querySelector('[data-global-notice-type="highspeed-share"]')).toBeNull();
  75. });
  76. });