useUiPluginRecommendations.test.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // @vitest-environment jsdom
  2. import { act, cleanup, renderHook } from "@testing-library/react";
  3. import { afterEach, expect, it, vi } from "vitest";
  4. import { useUiPluginRecommendations } from "@/plugin-ui/adapters/useUiPluginRecommendations.js";
  5. const context = vi.hoisted(() => ({ service: { getSnapshot: vi.fn() } }));
  6. vi.mock("@/hooks/useServices.js", () => ({
  7. useOptionalServices: () => ({ clientConfigService: context.service }),
  8. }));
  9. vi.mock("@/logger.js", () => ({ logger: { warn: vi.fn() } }));
  10. afterEach(cleanup);
  11. const recommendations = [{ pluginId: "panel@example", surfaceId: "main" }];
  12. it("禁用不请求,启用读取,关闭后忽略迟到结果", async () => {
  13. const pending = Promise.withResolvers<{ uiPluginRecommendations: typeof recommendations }>();
  14. context.service = { getSnapshot: vi.fn().mockReturnValue(pending.promise) };
  15. const { result, rerender } = renderHook(({ enabled }) => useUiPluginRecommendations(enabled), {
  16. initialProps: { enabled: false },
  17. });
  18. expect(context.service.getSnapshot).not.toHaveBeenCalled();
  19. expect(result.current.loading).toBe(false);
  20. rerender({ enabled: true });
  21. expect(result.current.loading).toBe(true);
  22. expect(context.service.getSnapshot).toHaveBeenCalledTimes(1);
  23. rerender({ enabled: false });
  24. await act(async () => pending.resolve({ uiPluginRecommendations: recommendations }));
  25. expect(result.current.recommendations).toEqual([]);
  26. });
  27. it("切换服务立即清空投影,丢弃旧服务迟到结果,失败为空", async () => {
  28. const pending = Promise.withResolvers<{ uiPluginRecommendations: typeof recommendations }>();
  29. context.service = { getSnapshot: vi.fn().mockReturnValue(pending.promise) };
  30. const { result, rerender } = renderHook(() => useUiPluginRecommendations(true));
  31. expect(result.current.loading).toBe(true);
  32. context.service = {
  33. getSnapshot: vi.fn().mockResolvedValue({ uiPluginRecommendations: recommendations }),
  34. };
  35. rerender();
  36. await act(async () => {});
  37. expect(result.current.recommendations).toEqual(recommendations);
  38. expect(result.current.loading).toBe(false);
  39. await act(async () => pending.resolve({ uiPluginRecommendations: [] }));
  40. expect(result.current.recommendations).toEqual(recommendations);
  41. expect(result.current.loading).toBe(false);
  42. context.service = { getSnapshot: vi.fn().mockRejectedValue(new Error("offline")) };
  43. rerender();
  44. expect(result.current.recommendations).toEqual([]);
  45. await act(async () => {});
  46. expect(result.current.recommendations).toEqual([]);
  47. expect(result.current.loading).toBe(false);
  48. });