rootAccountRefreshLifecycle.test.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // @vitest-environment jsdom
  2. import { renderHook, waitFor } from "@testing-library/react";
  3. import { describe, expect, it, vi } from "vitest";
  4. import type { IServiceAccessor } from "@zcode/services";
  5. import type { IPlatformService } from "@zcode/shared";
  6. import { useRootOAuthEffects } from "@/root/useRootOAuthEffects.js";
  7. import { logger } from "@/logger.js";
  8. vi.mock("@/hooks/useAlertDialog.js", () => ({ useAlertDialog: () => vi.fn() }));
  9. vi.mock("@/i18n/IntlProvider.js", () => ({
  10. useZCodeIntl: () => ({ intl: { formatMessage: ({ id }: { id: string }) => id } }),
  11. }));
  12. vi.mock("@/logger.js", () => ({
  13. logger: {
  14. info: vi.fn(),
  15. warn: vi.fn(),
  16. error: vi.fn(),
  17. lifecycle: { warn: vi.fn() },
  18. },
  19. }));
  20. describe("Root 账号刷新生命周期", () => {
  21. it("启动刷新失败后仍订阅后续账号事实,卸载时取消订阅", async () => {
  22. const dispose = vi.fn();
  23. const onDidChange = vi.fn(() => ({ dispose }));
  24. const services = {
  25. oauthService: { restoreCachedSessionState: vi.fn(async () => ({ status: "signed-out" })) },
  26. broadcastService: { onMessage: vi.fn(() => ({ dispose: vi.fn() })) },
  27. providerSettingsService: {
  28. onDidChange,
  29. getView: vi.fn(async () => ({ revision: 1, providers: [] })),
  30. },
  31. } as unknown as IServiceAccessor;
  32. const refreshProviderState = vi.fn(async () => {
  33. throw new Error("temporary refresh failure");
  34. });
  35. // 订阅已拆到独立 hook;真实挂载全部 effect,不能再假定第一个 effect 负责订阅。
  36. const { unmount } = renderHook(() =>
  37. useRootOAuthEffects({
  38. accountIntentKey: "test-account/individual",
  39. platform: {
  40. onOAuthCallback: vi.fn(() => vi.fn()),
  41. notifyRendererReady: vi.fn(),
  42. } as unknown as IPlatformService,
  43. services,
  44. refreshProviderState,
  45. setUser: vi.fn(),
  46. setIsRestoringOAuthSession: vi.fn(),
  47. setOAuthError: vi.fn(),
  48. oauthPollingActive: false,
  49. setOAuthPollingActive: vi.fn(),
  50. markOAuthSuccess: vi.fn(),
  51. onReauthenticationRequired: vi.fn(),
  52. }),
  53. );
  54. try {
  55. await waitFor(() =>
  56. expect(logger.warn).toHaveBeenCalledWith("[Root] 启动账号配置刷新失败,继续观察后续更新", {
  57. error: expect.any(Error),
  58. }),
  59. );
  60. expect(refreshProviderState).toHaveBeenCalledOnce();
  61. expect(onDidChange).toHaveBeenCalledOnce();
  62. expect(dispose).not.toHaveBeenCalled();
  63. } finally {
  64. unmount();
  65. }
  66. expect(dispose).toHaveBeenCalledOnce();
  67. });
  68. });