useOnboardingTrigger.test.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. // @vitest-environment jsdom
  2. import { act, renderHook, waitFor } from "@testing-library/react";
  3. import { describe, expect, it, vi } from "vitest";
  4. import type { OnboardingSettingsSyncPatch } from "@zcode/services";
  5. import { useOnboardingTrigger } from "@/onboarding/useOnboardingTrigger.js";
  6. import type { IOnboardingRecordService } from "@zcode/services";
  7. /**
  8. * CR 修复回归:useOnboardingTrigger 曾因坏 copy-paste 把 useState/useRef 嵌进
  9. * useEffect 回调(Rules of Hooks 违规,挂载即抛 "Invalid hook call"),且内层
  10. * setNeedsOnboarding 写的是被遮蔽的 state,触发/超时/回填全部死链。该缺陷
  11. * typecheck/lint/存量测试均不可见,必须用真实渲染覆盖。
  12. */
  13. function createRecordService(
  14. overrides: Partial<IOnboardingRecordService> = {},
  15. ): IOnboardingRecordService {
  16. return {
  17. appendRecord: async () => {},
  18. dismissOnboarding: async () => {},
  19. claimAnonymousRecord: async () => {},
  20. shouldOnboard: async () => true,
  21. getLatestEntry: async () => null,
  22. syncSettingsFromRecord: async () => null,
  23. updateRecordPreferences: async () => {},
  24. getRecords: async () => null,
  25. clearRecords: async () => {},
  26. ...overrides,
  27. };
  28. }
  29. function renderTrigger(options: {
  30. service: IOnboardingRecordService | null;
  31. userId?: string | null;
  32. hasStoredOccupation?: boolean;
  33. }) {
  34. const update = vi.fn(async () => {});
  35. const utils = renderHook(
  36. ({ userId }: { userId: string | null }) =>
  37. useOnboardingTrigger({
  38. onboardingRecord: options.service,
  39. userId,
  40. hasStoredOccupation: options.hasStoredOccupation ?? false,
  41. loadDeviceMid: () => "device-a",
  42. update,
  43. }),
  44. { initialProps: { userId: options.userId ?? null } },
  45. );
  46. return { ...utils, update };
  47. }
  48. describe("useOnboardingTrigger", () => {
  49. it("挂载不抛 hook 规则错误,并按 shouldOnboard=false 输出判定", async () => {
  50. const service = createRecordService({ shouldOnboard: async () => false });
  51. const { result } = renderTrigger({ service });
  52. // 修复前:effect 内的 useState 在挂载时同步抛 "Invalid hook call"
  53. await waitFor(() => expect(result.current[0]).toBe(false));
  54. });
  55. it("shouldOnboard=true 时输出需要引导;markOnboarded 置回 false", async () => {
  56. const service = createRecordService({ shouldOnboard: async () => true });
  57. const { result } = renderTrigger({ service });
  58. await waitFor(() => expect(result.current[0]).toBe(true));
  59. act(() => {
  60. result.current[1]();
  61. });
  62. expect(result.current[0]).toBe(false);
  63. });
  64. it("服务不可用退回 settings 判定(hasStoredOccupation=false 视为需引导)", async () => {
  65. const { result } = renderTrigger({ service: null, hasStoredOccupation: false });
  66. await waitFor(() => expect(result.current[0]).toBe(true));
  67. });
  68. it("挂载首跑不回填 settings;userId 运行时变化才按 record 回填", async () => {
  69. const patch: OnboardingSettingsSyncPatch = { onboardingOccupation: "finance" };
  70. const sync = vi.fn(async () => patch);
  71. const service = createRecordService({
  72. shouldOnboard: async () => false,
  73. syncSettingsFromRecord: sync,
  74. });
  75. const { result, rerender, update } = renderTrigger({ service, userId: null });
  76. // 首跑(null→已恢复的 id 不算运行时变化):判定但不回填
  77. rerender({ userId: "u1" });
  78. await waitFor(() => expect(result.current[0]).toBe(false));
  79. expect(sync).not.toHaveBeenCalled();
  80. expect(update).not.toHaveBeenCalled();
  81. // 换号(u1→u2,非空直切):按 record 回填
  82. rerender({ userId: "u2" });
  83. await waitFor(() => expect(sync).toHaveBeenCalled());
  84. await waitFor(() =>
  85. expect(update).toHaveBeenCalledWith(
  86. expect.objectContaining({ onboardingOccupation: "finance" }),
  87. ),
  88. );
  89. });
  90. it("登出(id→null)也按 null 用户的 record 回填", async () => {
  91. const patch: OnboardingSettingsSyncPatch = { onboardingOccupation: "other" };
  92. const sync = vi.fn(async () => patch);
  93. const service = createRecordService({
  94. shouldOnboard: async () => false,
  95. syncSettingsFromRecord: sync,
  96. });
  97. const { result, rerender, update } = renderTrigger({ service, userId: "u1" });
  98. await waitFor(() => expect(result.current[0]).toBe(false));
  99. rerender({ userId: null });
  100. await waitFor(() => expect(update).toHaveBeenCalledWith(expect.objectContaining(patch)));
  101. });
  102. it("登录后先认领再判定:认领使判定不触发(同一人不重复引导)", async () => {
  103. // shouldOnboard 返回 true 表示"若无认领会弹引导";认领先行由服务层保证一致性,
  104. // 这里验证调用顺序:claim 必须在 shouldOnboard 之前完成。
  105. const calls: string[] = [];
  106. const service = createRecordService({
  107. claimAnonymousRecord: async () => {
  108. calls.push("claim");
  109. },
  110. shouldOnboard: async () => {
  111. calls.push("shouldOnboard");
  112. return true;
  113. },
  114. });
  115. const { result } = renderTrigger({ service, userId: "u1" });
  116. await waitFor(() => expect(result.current[0]).toBe(true));
  117. expect(calls.indexOf("claim")).toBeLessThan(calls.indexOf("shouldOnboard"));
  118. });
  119. it("shouldOnboard RPC 挂起时 3 秒超时兜底退回 settings 判定", { timeout: 8000 }, async () => {
  120. const service = createRecordService({
  121. shouldOnboard: () => new Promise<boolean>(() => {}),
  122. });
  123. const { result } = renderTrigger({ service, hasStoredOccupation: false });
  124. await waitFor(() => expect(result.current[0]).toBe(true), { timeout: 5000 });
  125. });
  126. });