rootOAuthCallbackCancellation.test.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { describe, expect, it, vi } from "vitest";
  2. const { effects, errorLog } = vi.hoisted(() => ({
  3. effects: [] as Array<() => unknown>,
  4. errorLog: vi.fn(),
  5. }));
  6. vi.mock("react", async (original) => ({
  7. ...(await original<typeof import("react")>()),
  8. useEffect: (effect: () => unknown) => effects.push(effect),
  9. useRef: (current: unknown) => ({ current }),
  10. }));
  11. vi.mock("@/hooks/useAlertDialog.js", () => ({ useAlertDialog: () => vi.fn() }));
  12. vi.mock("@/i18n/IntlProvider.js", () => ({
  13. useZCodeIntl: () => ({ intl: { formatMessage: () => "登录失败" } }),
  14. }));
  15. vi.mock("@/root/useAccountConnectionLossNotification.js", () => ({
  16. useAccountConnectionLossNotification: vi.fn(),
  17. }));
  18. vi.mock("@/logger.js", () => ({
  19. logger: { info: vi.fn(), warn: vi.fn(), error: errorLog },
  20. }));
  21. import { useRootOAuthEffects } from "@/root/useRootOAuthEffects.js";
  22. describe("失效 OAuth 回调", () => {
  23. it.each([true, false])("pollingActive=%s 时静默忽略取消结果", async (oauthPollingActive) => {
  24. effects.length = 0;
  25. errorLog.mockClear();
  26. let callback!: (url: string) => Promise<void>;
  27. const setUser = vi.fn();
  28. const setOAuthError = vi.fn();
  29. const markOAuthSuccess = vi.fn();
  30. const setOAuthPollingActive = vi.fn();
  31. useRootOAuthEffects({
  32. accountIntentKey: "test",
  33. platform: {
  34. notifyRendererReady: vi.fn(),
  35. onOAuthCallback: (handler: typeof callback) => {
  36. callback = handler;
  37. return vi.fn();
  38. },
  39. } as never,
  40. services: {
  41. oauthService: { handleCallback: vi.fn(async () => null) },
  42. broadcastService: {},
  43. } as never,
  44. refreshProviderState: vi.fn(async () => {}),
  45. setUser,
  46. setIsRestoringOAuthSession: vi.fn(),
  47. setOAuthError,
  48. oauthPollingActive,
  49. setOAuthPollingActive,
  50. markOAuthSuccess,
  51. onReauthenticationRequired: vi.fn(),
  52. });
  53. // 只挂载回调订阅;启动恢复和轮询在各自测试中验证。
  54. effects.at(-1)!();
  55. await callback("zcode://oauth/callback?state=cancelled");
  56. expect(errorLog).not.toHaveBeenCalled();
  57. expect(setUser).not.toHaveBeenCalled();
  58. expect(setOAuthError).not.toHaveBeenCalled();
  59. expect(markOAuthSuccess).not.toHaveBeenCalled();
  60. expect(setOAuthPollingActive).not.toHaveBeenCalled();
  61. });
  62. });