useOnboardingTrigger.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. * 兜底语义(2026-10 第二次修订,docs/onboarding-record-spec.md §6):超时/rejection/
  14. * 服务不可用一律保守判"不需要引导",settings 不再参与资格判定——settings 兜底会把
  15. * "没填过引导的老用户"误判成需要引导(线上 dev 案例:登录瞬间判定早于任务索引回填,
  16. * shouldOnboard 真实返回 true 误弹;failure 兜底是同一冲突的第二入口)。真新用户在
  17. * 故障场景最坏晚一次启动再弹。
  18. *
  19. * 放行预算跨判定轮次共享:身份变化触发的重跑只使用剩余预算,且已有结果时后续轮次
  20. * 的超时兜底不生效。
  21. */
  22. function createRecordService(
  23. overrides: Partial<IOnboardingRecordService> = {},
  24. ): IOnboardingRecordService {
  25. return {
  26. appendRecord: async () => {},
  27. dismissOnboarding: async () => {},
  28. claimAnonymousRecord: async () => {},
  29. shouldOnboard: async () => true,
  30. getLatestEntry: async () => null,
  31. syncSettingsFromRecord: async () => null,
  32. updateRecordPreferences: async () => {},
  33. getRecords: async () => null,
  34. clearRecords: async () => {},
  35. ...overrides,
  36. };
  37. }
  38. type TriggerProps = {
  39. service: IOnboardingRecordService | null;
  40. userId?: string | null;
  41. };
  42. function renderTrigger(options: TriggerProps) {
  43. const update = vi.fn(async () => {});
  44. // 与真实调用方一致:loadDeviceMid 用稳定引用(useCallback),避免测试里
  45. // 每次渲染新建函数导致 effect 无意义重跑,干扰重跑次数断言。
  46. const loadDeviceMid = () => "device-a";
  47. const utils = renderHook(
  48. ({ userId }: { userId: string | null }) =>
  49. useOnboardingTrigger({
  50. onboardingRecord: options.service,
  51. userId,
  52. loadDeviceMid,
  53. update,
  54. }),
  55. {
  56. initialProps: { userId: options.userId ?? null },
  57. },
  58. );
  59. return { ...utils, update };
  60. }
  61. describe("useOnboardingTrigger", () => {
  62. it("挂载不抛 hook 规则错误,并按 shouldOnboard=false 输出判定", async () => {
  63. const service = createRecordService({ shouldOnboard: async () => false });
  64. const { result } = renderTrigger({ service });
  65. // 修复前:effect 内的 useState 在挂载时同步抛 "Invalid hook call"
  66. await waitFor(() => expect(result.current[0]).toBe(false));
  67. });
  68. it("shouldOnboard=true 时输出需要引导;markOnboarded 置回 false", async () => {
  69. const service = createRecordService({ shouldOnboard: async () => true });
  70. const { result } = renderTrigger({ service });
  71. await waitFor(() => expect(result.current[0]).toBe(true));
  72. act(() => {
  73. result.current[1]();
  74. });
  75. expect(result.current[0]).toBe(false);
  76. });
  77. it("服务不可用保守判不引导,不依赖 settings", async () => {
  78. // 无记录服务的宿主(home-only web 视图、测试 double)恒不自动弹;
  79. // 旧实现退回 settings 判定会把没填过引导的老用户误弹。
  80. const { result } = renderTrigger({ service: null });
  81. await act(async () => {});
  82. expect(result.current[0]).toBe(false);
  83. });
  84. it("挂载首跑不回填 settings;userId 运行时变化才按 record 回填", async () => {
  85. const patch: OnboardingSettingsSyncPatch = { onboardingOccupation: "finance" };
  86. const sync = vi.fn(async () => patch);
  87. const service = createRecordService({
  88. shouldOnboard: async () => false,
  89. syncSettingsFromRecord: sync,
  90. });
  91. const { result, rerender, update } = renderTrigger({ service, userId: null });
  92. // 首跑(null→已恢复的 id 不算运行时变化):判定但不回填
  93. rerender({ userId: "u1" });
  94. await waitFor(() => expect(result.current[0]).toBe(false));
  95. expect(sync).not.toHaveBeenCalled();
  96. expect(update).not.toHaveBeenCalled();
  97. // 换号(u1→u2,非空直切):按 record 回填
  98. rerender({ userId: "u2" });
  99. await waitFor(() => expect(sync).toHaveBeenCalled());
  100. await waitFor(() =>
  101. expect(update).toHaveBeenCalledWith(
  102. expect.objectContaining({ onboardingOccupation: "finance" }),
  103. ),
  104. );
  105. });
  106. it("登出(id→null)也按 null 用户的 record 回填", async () => {
  107. const patch: OnboardingSettingsSyncPatch = { onboardingOccupation: "other" };
  108. const sync = vi.fn(async () => patch);
  109. const service = createRecordService({
  110. shouldOnboard: async () => false,
  111. syncSettingsFromRecord: sync,
  112. });
  113. const { result, rerender, update } = renderTrigger({ service, userId: "u1" });
  114. await waitFor(() => expect(result.current[0]).toBe(false));
  115. rerender({ userId: null });
  116. await waitFor(() => expect(update).toHaveBeenCalledWith(expect.objectContaining(patch)));
  117. });
  118. it("登录后先认领再判定:认领使判定不触发(同一人不重复引导)", async () => {
  119. // shouldOnboard 返回 true 表示"若无认领会弹引导";认领先行由服务层保证一致性,
  120. // 这里验证调用顺序:claim 必须在 shouldOnboard 之前完成。
  121. const calls: string[] = [];
  122. const service = createRecordService({
  123. claimAnonymousRecord: async () => {
  124. calls.push("claim");
  125. },
  126. shouldOnboard: async () => {
  127. calls.push("shouldOnboard");
  128. return true;
  129. },
  130. });
  131. const { result } = renderTrigger({ service, userId: "u1" });
  132. await waitFor(() => expect(result.current[0]).toBe(true));
  133. expect(calls.indexOf("claim")).toBeLessThan(calls.indexOf("shouldOnboard"));
  134. });
  135. it("shouldOnboard RPC 挂起时 3 秒超时保守判为不引导", { timeout: 8000 }, async () => {
  136. // 超时只代表"结果未知",必须保守判 false;真实结果到达后照常覆盖(见下一用例)。
  137. const service = createRecordService({
  138. shouldOnboard: () => new Promise<boolean>(() => {}),
  139. });
  140. const { result } = renderTrigger({ service });
  141. await waitFor(() => expect(result.current[0]).toBe(false), { timeout: 5000 });
  142. });
  143. it(
  144. "超时保守判定后真实结果到达会覆盖:真新用户的引导只是晚几秒出现",
  145. { timeout: 8000 },
  146. async () => {
  147. let resolveShouldOnboard: ((value: boolean) => void) | undefined;
  148. const service = createRecordService({
  149. shouldOnboard: () =>
  150. new Promise<boolean>((resolve) => {
  151. resolveShouldOnboard = resolve;
  152. }),
  153. });
  154. const { result } = renderTrigger({ service });
  155. // 超时先到:保守 false,主界面先行
  156. await waitFor(() => expect(result.current[0]).toBe(false), { timeout: 5000 });
  157. // 真实结果(真新用户=true)迟到:覆盖为 true,引导补弹
  158. await act(async () => {
  159. resolveShouldOnboard?.(true);
  160. });
  161. await waitFor(() => expect(result.current[0]).toBe(true));
  162. },
  163. );
  164. it("shouldOnboard 失败保守判不引导,不退回 settings 判定", async () => {
  165. // rejection 兜底若读 settings(!onboardingOccupation),没填过引导的老用户
  166. // 会被误判成需要引导;未知结果必须判 false。
  167. const service = createRecordService({
  168. shouldOnboard: () => Promise.reject(new Error("rpc failed")),
  169. });
  170. const { result } = renderTrigger({ service });
  171. await waitFor(() => expect(result.current[0]).toBe(false));
  172. });
  173. it(
  174. "userId 变化重跑不重置放行预算:主界面总等待不超过首个判定轮的 3 秒",
  175. { timeout: 8000 },
  176. async () => {
  177. // 身份变化触发重跑时只使用剩余预算:首轮预算走到 2.9s 后换号重跑,
  178. // 3.1s(原截止后 0.1s)必须已保守放行,不得重启完整 3 秒。
  179. vi.useFakeTimers();
  180. try {
  181. const service = createRecordService({
  182. claimAnonymousRecord: () => new Promise<void>(() => {}),
  183. shouldOnboard: () => new Promise<boolean>(() => {}),
  184. });
  185. const { result, rerender } = renderTrigger({ service });
  186. // 首轮预算走到 2.9s(判定 RPC 挂起,未放行),换号触发重跑
  187. await act(async () => {
  188. await vi.advanceTimersByTimeAsync(2900);
  189. });
  190. rerender({ userId: "u2" });
  191. // 旧实现此处重启完整 3 秒;共享预算后只剩 0.1s——3.1s 必须已放行
  192. await act(async () => {
  193. await vi.advanceTimersByTimeAsync(200);
  194. });
  195. expect(result.current[0]).toBe(false);
  196. } finally {
  197. vi.useRealTimers();
  198. }
  199. },
  200. );
  201. it(
  202. "已有判定结果时后续轮次的超时兜底不再生效,不翻掉进行中的引导",
  203. { timeout: 8000 },
  204. async () => {
  205. // 预算分离的另一半语义:首轮真实结果 true(引导展示中)后身份变化触发重跑,
  206. // 若重跑的 RPC 挂起,其超时兜底不得把 true 翻成 false 让引导消失。
  207. vi.useFakeTimers();
  208. try {
  209. let calls = 0;
  210. const service = createRecordService({
  211. shouldOnboard: () => {
  212. calls += 1;
  213. // 首轮立即判 true(真新用户);第二轮(换号后)挂起
  214. return calls === 1 ? Promise.resolve(true) : new Promise<boolean>(() => {});
  215. },
  216. });
  217. const { result, rerender } = renderTrigger({ service });
  218. // fake timers 下不能用 waitFor(轮询定时器被 fake 永不推进);
  219. // 首轮立即 resolve,act 刷微任务后直接断言。
  220. await act(async () => {});
  221. expect(result.current[0]).toBe(true);
  222. rerender({ userId: "u2" });
  223. // 第二轮挂起,即使推过 3 秒也不得翻转首轮的 true
  224. await act(async () => {
  225. await vi.advanceTimersByTimeAsync(3500);
  226. });
  227. expect(result.current[0]).toBe(true);
  228. } finally {
  229. vi.useRealTimers();
  230. }
  231. },
  232. );
  233. it("userId 变化会重跑判定(幂等第二轮)", async () => {
  234. // 换号后按新身份重新判定(A 已答不弹,B 未答 → B 触发引导)。
  235. let calls = 0;
  236. const service = createRecordService({
  237. shouldOnboard: async () => {
  238. calls += 1;
  239. return calls > 1;
  240. },
  241. });
  242. const { result, rerender } = renderTrigger({ service, userId: "u1" });
  243. // 第一轮(u1 已答)返回 false;换号 u2 重跑第二轮返回 true
  244. await waitFor(() => expect(result.current[0]).toBe(false));
  245. rerender({ userId: "u2" });
  246. await waitFor(() => expect(result.current[0]).toBe(true));
  247. expect(calls).toBe(2);
  248. });
  249. });