api.test.js 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235
  1. /**
  2. * Tests for cfc-frontend utils/api.js
  3. *
  4. * Mocks uni.request to intercept and verify API calls.
  5. */
  6. import * as api from '@/utils/api'
  7. // --------------- helpers ---------------
  8. /** Helper: make uni.request call success(data) on next tick */
  9. function mockSuccess(data) {
  10. global.uni.request.mockImplementation((opts) => {
  11. process.nextTick(() => {
  12. if (opts.success) opts.success({ data })
  13. })
  14. })
  15. }
  16. /** Helper: make uni.request call fail(err) on next tick */
  17. function mockFail(err) {
  18. global.uni.request.mockImplementation((opts) => {
  19. process.nextTick(() => {
  20. if (opts.fail) opts.fail(err)
  21. })
  22. })
  23. }
  24. function mockSequence(responses) {
  25. var i = 0
  26. global.uni.request.mockImplementation((opts) => {
  27. var resp = responses[Math.min(i, responses.length - 1)]
  28. i++
  29. process.nextTick(() => {
  30. if (resp.err) {
  31. if (opts.fail) opts.fail(resp.err)
  32. } else {
  33. if (opts.success) opts.success({ data: resp.data })
  34. }
  35. })
  36. })
  37. }
  38. // --------------- global beforeEach ---------------
  39. beforeEach(() => {
  40. global.uni._storage = {}
  41. global.uni.request.mockReset()
  42. global.uni.showToast.mockReset()
  43. global.uni.reLaunch.mockReset()
  44. global.uni.login.mockReset()
  45. global.getCurrentPages.mockReset()
  46. global.getCurrentPages.mockReturnValue([{ route: 'pages/index-home/index' }])
  47. global.uni.getAccountInfoSync.mockReset()
  48. global.uni.getAccountInfoSync.mockReturnValue({
  49. miniProgram: { envVersion: 'develop' }
  50. })
  51. // api.js 的 3 秒请求去重缓存是模块级单例,跨用例残留会让后续用例拿到上一个用例缓存的
  52. // Promise(同 URL+method+body),表现为「本该 401 却是 200」「lastRequest() 为 undefined」。
  53. // 每个用例前显式清空,保证用例间隔离。
  54. api.clearApiDedup()
  55. })
  56. /** Capture the last uni.request call options */
  57. function lastRequest() {
  58. const calls = global.uni.request.mock.calls
  59. return calls[calls.length - 1][0]
  60. }
  61. // --------------- auth module ---------------
  62. describe('auth API', () => {
  63. beforeEach(() => {
  64. global.uni._storage.token = 'test-token'
  65. global.uni._storage.userId = '42'
  66. })
  67. test('wechatLogin sends POST /api/auth/wechat-login', async () => {
  68. mockSuccess({ code: 200, data: { token: 'jwt' } })
  69. const res = await api.wechatLogin('code123', { nickname: 'test' })
  70. const opts = lastRequest()
  71. expect(opts.method).toBe('POST')
  72. expect(opts.url).toMatch(/\/api\/auth\/wechat-login$/)
  73. expect(opts.data.code).toBe('code123')
  74. expect(res.data.token).toBe('jwt')
  75. })
  76. test('phoneLogin sends POST with phone and code', async () => {
  77. mockSuccess({ code: 200, data: { token: 'jwt' } })
  78. await api.phoneLogin({ phone: '13800138000', code: '1234' })
  79. const opts = lastRequest()
  80. expect(opts.method).toBe('POST')
  81. expect(opts.url).toMatch(/\/api\/auth\/phone-login$/)
  82. expect(opts.data.phone).toBe('13800138000')
  83. })
  84. test('sendCode sends POST with data', async () => {
  85. mockSuccess({ code: 200 })
  86. await api.sendCode({ phone: '13800138000' })
  87. const opts = lastRequest()
  88. expect(opts.method).toBe('POST')
  89. expect(opts.url).toMatch(/\/api\/auth\/send-code$/)
  90. })
  91. test('silentLogin sends POST with code', async () => {
  92. mockSuccess({ code: 200 })
  93. await api.silentLogin('wxcode')
  94. expect(lastRequest().data.code).toBe('wxcode')
  95. })
  96. // 已废弃:后端 /api/auth/auto-login 已改为 410 Gone(裸 openid 换 token 属越权漏洞)。
  97. // 导出仅为排查历史调用保留,不得在新代码中使用;续期请走 silentRelogin()。
  98. test('autoLogin (deprecated) still targets /api/auth/auto-login', async () => {
  99. mockSuccess({ code: 410, message: '该接口已废弃,请改用 /api/auth/silent-login' })
  100. await expect(api.autoLogin('openid_xxx')).rejects.toEqual(
  101. { code: 410, message: '该接口已废弃,请改用 /api/auth/silent-login' }
  102. )
  103. const opts = lastRequest()
  104. expect(opts.url).toMatch(/\/api\/auth\/auto-login$/)
  105. expect(opts.data.openid).toBe('openid_xxx')
  106. })
  107. test('setPassword and verifyPassword send correct endpoints', async () => {
  108. mockSuccess({ code: 200 })
  109. await api.setPassword('secret')
  110. expect(lastRequest().url).toMatch(/\/api\/auth\/set-password$/)
  111. expect(lastRequest().data.password).toBe('secret')
  112. await api.verifyPassword('secret')
  113. expect(lastRequest().url).toMatch(/\/api\/auth\/verify-password$/)
  114. })
  115. test('directRegister sends POST', async () => {
  116. mockSuccess({ code: 200 })
  117. await api.directRegister({ phone: '13800138000', nickname: 'tester' })
  118. expect(lastRequest().url).toMatch(/\/api\/auth\/direct-register$/)
  119. })
  120. test('checkPhone sends POST with phone', async () => {
  121. mockSuccess({ code: 200 })
  122. await api.checkPhone('13800138000')
  123. expect(lastRequest().data.phone).toBe('13800138000')
  124. })
  125. test('wechatPhoneLogin sends POST', async () => {
  126. mockSuccess({ code: 200 })
  127. await api.wechatPhoneLogin({ code: 'wxcode', iv: 'iv', encryptedData: 'enc' })
  128. expect(lastRequest().url).toMatch(/\/api\/auth\/wechat-phone-login$/)
  129. })
  130. test('verifyToken sends POST /api/auth/verify with bearer token', async () => {
  131. mockSuccess({ code: 200, data: { userId: 42, role: 'parent' } })
  132. const res = await api.verifyToken()
  133. const opts = lastRequest()
  134. expect(opts.method).toBe('POST')
  135. expect(opts.url).toMatch(/\/api\/auth\/verify$/)
  136. expect(opts.header.Authorization).toBe('Bearer test-token')
  137. expect(res.data.userId).toBe(42)
  138. })
  139. test('verifyToken with 401 (token expired) clears auth and redirects to login', async () => {
  140. jest.useFakeTimers()
  141. mockSuccess({ code: 401, message: 'Token无效或已过期', data: null })
  142. await expect(api.verifyToken()).rejects.toEqual({ code: 401, message: 'Token无效或已过期', data: null })
  143. expect(global.uni._storage.token).toBeUndefined()
  144. // 触发 _clearAuthAndRedirect 内 1.5s setTimeout(reLaunch 在此定时器回调中执行)
  145. jest.runAllTimers()
  146. expect(global.uni.reLaunch).toHaveBeenCalledWith({ url: '/pages/login/login' })
  147. expect(global.uni.showToast).toHaveBeenCalled()
  148. jest.useRealTimers()
  149. })
  150. test('verifyToken with 401 (user deleted) clears auth and redirects to login', async () => {
  151. jest.useFakeTimers()
  152. mockSuccess({ code: 401, message: '用户不存在', data: null })
  153. await expect(api.verifyToken()).rejects.toEqual({ code: 401, message: '用户不存在', data: null })
  154. expect(global.uni._storage.token).toBeUndefined()
  155. jest.runAllTimers()
  156. expect(global.uni.reLaunch).toHaveBeenCalledWith({ url: '/pages/login/login' })
  157. expect(global.uni.showToast).toHaveBeenCalled()
  158. jest.useRealTimers()
  159. })
  160. // 静默续期 = uni.login() 取微信签发的一次性 code → /api/auth/silent-login(服务端 code2Session)。
  161. // 本地 openid 只作为「本设备曾登录过」的触发条件,不作为凭证上送。
  162. function mockUniLoginCode(code) {
  163. global.uni.login.mockImplementation((opts) => {
  164. process.nextTick(() => {
  165. if (opts.success) opts.success({ code: code || 'wxcode' })
  166. })
  167. })
  168. }
  169. test('401 silently re-logins via wx.login + code2Session and retries original request', async () => {
  170. global.uni.reLaunch.mockReset()
  171. global.uni.showToast.mockReset()
  172. global.uni._storage.openid = 'openid_abc'
  173. global.uni._storage.token = 'expired-token'
  174. mockUniLoginCode('fresh-wxcode')
  175. mockSequence([
  176. { data: { code: 401, message: 'Token无效或已过期', data: null } },
  177. { data: { code: 200, data: { token: 'new-jwt', userId: 42, role: 'parent', familyId: 1, openid: 'openid_abc' } } },
  178. { data: { code: 200, data: { userId: 42, role: 'parent' } } }
  179. ])
  180. const res = await api.verifyToken()
  181. expect(res.data.userId).toBe(42)
  182. expect(global.uni._storage.token).toBe('new-jwt')
  183. // 续期必须走 code2Session,且不得把 openid 当凭证发送
  184. const calls = global.uni.request.mock.calls.map((c) => c[0])
  185. const renewReq = calls.find((c) => /\/api\/auth\/silent-login/.test(c.url))
  186. expect(renewReq).toBeDefined()
  187. expect(renewReq.data.code).toBe('fresh-wxcode')
  188. expect(renewReq.data.openid).toBeUndefined()
  189. // 已废弃的裸 openid 换 token 接口不得被调用
  190. expect(calls.find((c) => /\/api\/auth\/auto-login/.test(c.url))).toBeUndefined()
  191. expect(global.uni.reLaunch).not.toHaveBeenCalled()
  192. expect(global.uni.showToast).not.toHaveBeenCalled()
  193. })
  194. // 回归:首页冷启动会并发打出多个 401(family/member/list、membership/my、onboarding/progress…)。
  195. // 修复前 _handle401 在 _reloginLock 为真时直接调 _clearAuthAndRedirect():
  196. // 第 1 个 401 刚启动 silentRelogin()(uni.login 异步),第 2、3 个 401 立刻把 token 从
  197. // storage 抹掉并预约 1500ms 后 reLaunch 登录页 → 在途续期被打断,
  198. // 线上表现为「控制台只有 401、没有任何续期日志、用户被弹回登录页」。
  199. test('concurrent 401s queue behind one renewal and all get replayed', async () => {
  200. global.uni._storage.openid = 'openid_abc'
  201. global.uni._storage.token = 'expired-token'
  202. mockUniLoginCode('fresh-wxcode')
  203. // 3 个业务请求同时 401 → 续期 1 次成功 → 3 个重放全部 200
  204. mockSequence([
  205. { data: { code: 401, message: 'Token无效或已过期', data: null } },
  206. { data: { code: 401, message: 'Token无效或已过期', data: null } },
  207. { data: { code: 401, message: 'Token无效或已过期', data: null } },
  208. { data: { code: 200, data: { token: 'new-jwt', userId: 42, role: 'parent', familyId: 1, openid: 'openid_abc' } } },
  209. { data: { code: 200, data: { ok: 'verify' } } },
  210. { data: { code: 200, data: { ok: 'members' } } },
  211. { data: { code: 200, data: { ok: 'membership' } } }
  212. ])
  213. const [verifyRes, memberRes, membershipRes] = await Promise.all([
  214. api.verifyToken(),
  215. api.getFamilyMemberList({}),
  216. api.getMyMembership()
  217. ])
  218. // 三个请求都必须拿到成功结果(修复前后两个会被 reject)
  219. expect(verifyRes.data.ok).toBe('verify')
  220. expect(memberRes.data.ok).toBe('members')
  221. expect(membershipRes.data.ok).toBe('membership')
  222. const calls = global.uni.request.mock.calls.map((c) => c[0])
  223. // 续期只发生一次,绝不能因并发 401 引发续期风暴
  224. expect(calls.filter((c) => /\/api\/auth\/silent-login/.test(c.url)).length).toBe(1)
  225. // token 必须是被续期后的新值,而不是被并发 401 抹掉
  226. expect(global.uni._storage.token).toBe('new-jwt')
  227. // 关键回归点:并发 401 不得触发「登录已过期」提示,也不得跳登录页
  228. expect(global.uni.showToast).not.toHaveBeenCalled()
  229. expect(global.uni.reLaunch).not.toHaveBeenCalled()
  230. })
  231. // 回归:重放请求若仍 401(刚签发的 token 依旧不可用),必须直接失败而不是重新入队,
  232. // 否则「续期 → 重放 → 401 → 续期 → 重放」会 ping-pong 死循环。
  233. test('replayed request that still 401 fails without triggering another renewal', async () => {
  234. global.uni._storage.openid = 'openid_abc'
  235. global.uni._storage.token = 'expired-token'
  236. mockUniLoginCode('fresh-wxcode')
  237. mockSequence([
  238. { data: { code: 401, message: 'Token无效或已过期', data: null } },
  239. { data: { code: 200, data: { token: 'new-jwt', userId: 42, role: 'parent', familyId: 1, openid: 'openid_abc' } } },
  240. { data: { code: 401, message: 'Token无效或已过期', data: null } }
  241. ])
  242. await expect(api.verifyToken()).rejects.toEqual({ code: 401, message: 'Token无效或已过期', data: null })
  243. const calls = global.uni.request.mock.calls.map((c) => c[0])
  244. // 只续期过一次,重放 401 不再触发第二次续期
  245. expect(calls.filter((c) => /\/api\/auth\/silent-login/.test(c.url)).length).toBe(1)
  246. expect(global.uni._storage.token).toBe('new-jwt')
  247. })
  248. test('401 retry does not duplicate query params in the replayed request URL', async () => {
  249. global.uni._storage.openid = 'openid_abc'
  250. global.uni._storage.token = 'expired-token'
  251. mockUniLoginCode('fresh-wxcode')
  252. mockSequence([
  253. { data: { code: 401, message: 'Token无效或已过期', data: null } },
  254. { data: { code: 200, data: { token: 'new-jwt', userId: 42, role: 'parent', familyId: 1, openid: 'openid_abc' } } },
  255. { data: { code: 200, data: { ok: true } } }
  256. ])
  257. // publishPackage 通过 options 传 query(?publish=true),是最容易暴露重复拼接的调用形态
  258. await api.publishPackage(7, true)
  259. const calls = global.uni.request.mock.calls.map((c) => c[0])
  260. const hits = calls.filter((c) => /\/api\/packages\/7\/publish/.test(c.url))
  261. expect(hits.length).toBe(2) // 原始请求 1 次 + 401 续期后重放 1 次
  262. // 修复前:_handle401 收到的是已拼过 query 的 url,重放时 options 又拼一次 → ?publish=true&publish=true
  263. hits.forEach((c) => {
  264. expect(c.url).toBe(c.url.split('?')[0] + '?publish=true')
  265. expect((c.url.match(/publish=/g) || []).length).toBe(1)
  266. })
  267. })
  268. test('401 during app launch window clears auth but does NOT navigate to login subpackage', async () => {
  269. jest.useFakeTimers()
  270. global.uni._storage.openid = 'openid_abc'
  271. global.uni._storage.token = 'expired-token'
  272. // 仍停在 splash:pages/login 是分包,此刻尚未下载,
  273. // reLaunch 过去会报 'Page "pages/login/login" has not been registered yet'
  274. global.getCurrentPages.mockReturnValue([{ route: 'pages/splash/index' }])
  275. mockUniLoginCode()
  276. mockSequence([
  277. { data: { code: 401, message: 'Token无效或已过期', data: null } },
  278. { data: { code: 500, message: '用户不存在,请先登录', data: null } }
  279. ])
  280. await expect(api.verifyToken()).rejects.toEqual({ code: 401, message: 'Token无效或已过期', data: null })
  281. jest.runAllTimers()
  282. // 登录态必须清掉
  283. expect(global.uni._storage.token).toBeUndefined()
  284. // 但启动窗口内绝不跳登录页,交由 splash 落地首页(主包)
  285. expect(global.uni.reLaunch).not.toHaveBeenCalled()
  286. jest.useRealTimers()
  287. })
  288. test('401 during app launch window (no page registered yet) also skips navigation', async () => {
  289. jest.useFakeTimers()
  290. global.uni._storage.openid = 'openid_abc'
  291. global.uni._storage.token = 'expired-token'
  292. // 首屏尚未注册,getCurrentPages() 为空
  293. global.getCurrentPages.mockReturnValue([])
  294. mockUniLoginCode()
  295. mockSequence([
  296. { data: { code: 401, message: 'Token无效或已过期', data: null } },
  297. { data: { code: 500, message: '用户不存在,请先登录', data: null } }
  298. ])
  299. await expect(api.verifyToken()).rejects.toEqual({ code: 401, message: 'Token无效或已过期', data: null })
  300. jest.runAllTimers()
  301. expect(global.uni._storage.token).toBeUndefined()
  302. expect(global.uni.reLaunch).not.toHaveBeenCalled()
  303. jest.useRealTimers()
  304. })
  305. test('401 falls back to login page when silent re-login is refused', async () => {
  306. jest.useFakeTimers()
  307. global.uni._storage.openid = 'openid_abc'
  308. global.uni._storage.token = 'expired-token'
  309. mockUniLoginCode()
  310. mockSequence([
  311. { data: { code: 401, message: 'Token无效或已过期', data: null } },
  312. { data: { code: 500, message: '用户不存在,请先登录', data: null } }
  313. ])
  314. await expect(api.verifyToken()).rejects.toEqual({ code: 401, message: 'Token无效或已过期', data: null })
  315. jest.runAllTimers()
  316. expect(global.uni.reLaunch).toHaveBeenCalledWith({ url: '/pages/login/login' })
  317. expect(global.uni.showToast).toHaveBeenCalled()
  318. jest.useRealTimers()
  319. })
  320. test('401 with no cached openid (never logged in on this device) goes straight to login', async () => {
  321. jest.useFakeTimers()
  322. global.uni._storage.token = 'expired-token'
  323. mockSequence([
  324. { data: { code: 401, message: 'Token无效或已过期', data: null } }
  325. ])
  326. await expect(api.verifyToken()).rejects.toEqual({ code: 401, message: 'Token无效或已过期', data: null })
  327. // 本设备从未登录过 → 不应调用 uni.login 浪费一次 code2Session
  328. expect(global.uni.login).not.toHaveBeenCalled()
  329. jest.runAllTimers()
  330. expect(global.uni.reLaunch).toHaveBeenCalledWith({ url: '/pages/login/login' })
  331. jest.useRealTimers()
  332. })
  333. test('silentRelogin returns null when wx.login yields no code', async () => {
  334. global.uni._storage.openid = 'openid_abc'
  335. global.uni.login.mockImplementation((opts) => {
  336. process.nextTick(() => { if (opts.success) opts.success({}) })
  337. })
  338. await expect(api.silentRelogin()).resolves.toBeNull()
  339. expect(global.uni.request).not.toHaveBeenCalled()
  340. })
  341. test('silentRelogin returns null when wx.login fails', async () => {
  342. global.uni._storage.openid = 'openid_abc'
  343. global.uni.login.mockImplementation((opts) => {
  344. process.nextTick(() => { if (opts.fail) opts.fail({ errMsg: 'login:fail' }) })
  345. })
  346. await expect(api.silentRelogin()).resolves.toBeNull()
  347. expect(global.uni.request).not.toHaveBeenCalled()
  348. })
  349. test('silentRelogin does not issue a renew request on 401 (no recursive renewal)', async () => {
  350. global.uni._storage.openid = 'openid_abc'
  351. global.uni._storage.token = 'expired-token'
  352. mockUniLoginCode()
  353. // 续期接口自身返回 401:必须直接失败,不能再触发一次 silentRelogin,否则会递归续期/误清登录态
  354. mockSuccess({ code: 401, message: 'Token无效或已过期', data: null })
  355. await expect(api.silentRelogin()).resolves.toBeNull()
  356. expect(global.uni.request.mock.calls.length).toBe(1)
  357. // 续期失败不得清空登录态(那是「主动登出」才做的事)
  358. expect(global.uni._storage.token).toBe('expired-token')
  359. expect(global.uni.reLaunch).not.toHaveBeenCalled()
  360. })
  361. test('Authorization header includes Bearer token', async () => {
  362. mockSuccess({ code: 200 })
  363. global.uni._storage.token = 'my-jwt-token'
  364. await api.getUserInfo()
  365. const opts = lastRequest()
  366. expect(opts.header.Authorization).toBe('Bearer my-jwt-token')
  367. })
  368. test('X-User-Id header is NOT sent (removed for security)', async () => {
  369. mockSuccess({ code: 200 })
  370. global.uni._storage.userId = '99'
  371. await api.getUserInfo()
  372. expect(lastRequest().header['X-User-Id']).toBeUndefined()
  373. })
  374. test('rejects on non-200 code', async () => {
  375. mockSuccess({ code: 400, message: 'Bad Request' })
  376. await expect(api.getUserInfo()).rejects.toEqual({ code: 400, message: 'Bad Request' })
  377. })
  378. test('rejects on network failure', async () => {
  379. mockFail(new Error('Network error'))
  380. await expect(api.getUserInfo()).rejects.toThrow('Network error')
  381. })
  382. })
  383. // --------------- streets module ---------------
  384. describe('street address API', () => {
  385. test('getProvinces sends POST to /api/streets/provinces', async () => {
  386. mockSuccess({ code: 200, data: [] })
  387. await api.getProvinces()
  388. expect(lastRequest().url).toMatch(/\/api\/streets\/provinces$/)
  389. })
  390. test('getStreetChildren sends POST with parentId', async () => {
  391. mockSuccess({ code: 200 })
  392. await api.getStreetChildren(110000)
  393. expect(lastRequest().url).toMatch(/\/api\/streets\/children\/110000$/)
  394. })
  395. test('getStreetById sends POST to correct URL', async () => {
  396. mockSuccess({ code: 200 })
  397. await api.getStreetById(110101)
  398. expect(lastRequest().url).toMatch(/\/api\/streets\/110101$/)
  399. })
  400. test('getStreetPath sends POST', async () => {
  401. mockSuccess({ code: 200 })
  402. await api.getStreetPath(110101)
  403. expect(lastRequest().url).toMatch(/\/api\/streets\/110101\/path$/)
  404. })
  405. test('searchStreet sends POST with keyword', async () => {
  406. mockSuccess({ code: 200 })
  407. await api.searchStreet('北京')
  408. expect(lastRequest().data.keyword).toBe('北京')
  409. })
  410. test('matchByStreet sends POST with streetId', async () => {
  411. mockSuccess({ code: 200 })
  412. await api.matchByStreet(110101)
  413. expect(lastRequest().url).toMatch(/\/110101\/match$/)
  414. })
  415. })
  416. // --------------- user / family module ---------------
  417. describe('user & family API', () => {
  418. test('getUserInfo sends POST', async () => {
  419. mockSuccess({ code: 200 })
  420. await api.getUserInfo()
  421. expect(lastRequest().url).toMatch(/\/api\/user\/info$/)
  422. })
  423. test('updateUserInfo sends POST with data', async () => {
  424. mockSuccess({ code: 200 })
  425. await api.updateUserInfo({ nickname: 'new-name' })
  426. expect(lastRequest().data.nickname).toBe('new-name')
  427. })
  428. test('joinFamily sends POST with inviteCode', async () => {
  429. mockSuccess({ code: 200 })
  430. await api.joinFamily('ABC123')
  431. expect(lastRequest().data.inviteCode).toBe('ABC123')
  432. })
  433. test('createFamily sends POST with name', async () => {
  434. mockSuccess({ code: 200 })
  435. await api.createFamily('幸福之家')
  436. expect(lastRequest().data.name).toBe('幸福之家')
  437. })
  438. test('getFamilyMemberList sends POST to unified endpoint', async () => {
  439. mockSuccess({ code: 200 })
  440. await api.getFamilyMemberList()
  441. expect(lastRequest().url).toMatch(/\/api\/family\/member\/list$/)
  442. })
  443. test('getFamilyMemberList sends visibleOnly param', async () => {
  444. mockSuccess({ code: 200 })
  445. await api.getFamilyMemberList({ visibleOnly: true })
  446. expect(lastRequest().url).toMatch(/\/api\/family\/member\/list$/)
  447. expect(lastRequest().data.visibleOnly).toBe(true)
  448. })
  449. test('getFamilyMemberList sends includeFamily param', async () => {
  450. mockSuccess({ code: 200 })
  451. await api.getFamilyMemberList({ includeFamily: true })
  452. expect(lastRequest().url).toMatch(/\/api\/family\/member\/list$/)
  453. expect(lastRequest().data.includeFamily).toBe(true)
  454. })
  455. test('updateMemberVisibility sends POST with params', async () => {
  456. mockSuccess({ code: 200 })
  457. await api.updateMemberVisibility(1, 'child', true)
  458. expect(lastRequest().data.memberId).toBe(1)
  459. expect(lastRequest().data.memberType).toBe('child')
  460. expect(lastRequest().data.showToFamily).toBe(true)
  461. })
  462. test('switchMode sends POST with mode', async () => {
  463. mockSuccess({ code: 200 })
  464. await api.switchMode('child')
  465. expect(lastRequest().data.mode).toBe('child')
  466. })
  467. test('switchToChild sends POST with memberId', async () => {
  468. mockSuccess({ code: 200 })
  469. await api.switchToChild(5)
  470. expect(lastRequest().data.memberId).toBe(5)
  471. })
  472. test('switchBackToParent sends POST', async () => {
  473. mockSuccess({ code: 200 })
  474. await api.switchBackToParent()
  475. expect(lastRequest().url).toMatch(/\/api\/user\/switch-back-to-parent$/)
  476. })
  477. test('getChildren sends POST to unified member list', async () => {
  478. mockSuccess({ code: 200 })
  479. await api.getChildren()
  480. expect(lastRequest().url).toMatch(/\/api\/family\/member\/list$/)
  481. })
  482. test('createChild sends POST with data', async () => {
  483. mockSuccess({ code: 200 })
  484. await api.createChild({ name: '小宝', gender: 'male' })
  485. expect(lastRequest().url).toMatch(/\/api\/family\/user\/children$/)
  486. expect(lastRequest().data.name).toBe('小宝')
  487. })
  488. test('updateChild sends POST merged with memberId', async () => {
  489. mockSuccess({ code: 200 })
  490. await api.updateChild(5, { nickname: '大宝' })
  491. expect(lastRequest().data.memberId).toBe(5)
  492. expect(lastRequest().data.nickname).toBe('大宝')
  493. })
  494. test('kickFamilyMember sends POST with targetUserId', async () => {
  495. mockSuccess({ code: 200 })
  496. await api.kickFamilyMember(10)
  497. expect(lastRequest().data.targetUserId).toBe(10)
  498. })
  499. })
  500. // --------------- membership module ---------------
  501. describe('membership API', () => {
  502. test('getMembershipLevels sends POST', async () => {
  503. mockSuccess({ code: 200 })
  504. await api.getMembershipLevels()
  505. expect(lastRequest().url).toMatch(/\/api\/membership\/levels$/)
  506. })
  507. test('getMyMembership sends POST', async () => {
  508. mockSuccess({ code: 200 })
  509. await api.getMyMembership()
  510. expect(lastRequest().url).toMatch(/\/api\/membership\/my$/)
  511. })
  512. test('createOrder sends POST with levelCode and paymentType', async () => {
  513. mockSuccess({ code: 200 })
  514. await api.createOrder('vip', 'wechat')
  515. expect(lastRequest().data.levelCode).toBe('vip')
  516. expect(lastRequest().data.paymentType).toBe('wechat')
  517. })
  518. })
  519. // --------------- tasks module ---------------
  520. describe('tasks API', () => {
  521. test('createTask sends POST with data', async () => {
  522. mockSuccess({ code: 200 })
  523. await api.createTask({ title: '晨读', memberId: 5 })
  524. expect(lastRequest().url).toMatch(/\/api\/tasks$/)
  525. expect(lastRequest().data.title).toBe('晨读')
  526. })
  527. test('getTodayTasks sends POST with memberId', async () => {
  528. mockSuccess({ code: 200 })
  529. await api.getTodayTasks(5)
  530. expect(lastRequest().data.memberId).toBe(5)
  531. })
  532. test('getPendingReviewTasks sends POST', async () => {
  533. mockSuccess({ code: 200 })
  534. await api.getPendingReviewTasks()
  535. expect(lastRequest().url).toMatch(/\/api\/tasks\/pending-review$/)
  536. })
  537. test('approveTask sends POST with approved:true', async () => {
  538. mockSuccess({ code: 200 })
  539. await api.approveTask(10)
  540. expect(lastRequest().url).toMatch(/\/api\/tasks\/10\/review$/)
  541. expect(lastRequest().data.approved).toBe(true)
  542. })
  543. test('rejectTask sends POST with approved:false', async () => {
  544. mockSuccess({ code: 200 })
  545. await api.rejectTask(10)
  546. expect(lastRequest().data.approved).toBe(false)
  547. })
  548. test('completeTask sends POST with memberId and photoUrl', async () => {
  549. mockSuccess({ code: 200 })
  550. await api.completeTask(10, 5, 'http://photo.url')
  551. expect(lastRequest().data.memberId).toBe(5)
  552. expect(lastRequest().data.photoUrl).toBe('http://photo.url')
  553. })
  554. test('reviewTask sends POST with data', async () => {
  555. mockSuccess({ code: 200 })
  556. await api.reviewTask(10, { approved: true, comment: '很好' })
  557. expect(lastRequest().url).toMatch(/\/api\/tasks\/10\/review$/)
  558. expect(lastRequest().data.comment).toBe('很好')
  559. })
  560. test('getTaskHistory sends POST with pagination', async () => {
  561. mockSuccess({ code: 200 })
  562. await api.getTaskHistory(5, 1, 20)
  563. expect(lastRequest().data.memberId).toBe(5)
  564. expect(lastRequest().data.page).toBe(1)
  565. expect(lastRequest().data.size).toBe(20)
  566. })
  567. test('deleteTask sends POST with _method DELETE', async () => {
  568. mockSuccess({ code: 200 })
  569. await api.deleteTask(10)
  570. expect(lastRequest().method).toBe('POST')
  571. expect(lastRequest().url).toMatch(/\/api\/tasks\/10$/)
  572. expect(lastRequest().data._method).toBe('DELETE')
  573. })
  574. test('batchCompleteTasks sends POST with array', async () => {
  575. mockSuccess({ code: 200 })
  576. await api.batchCompleteTasks([1, 2, 3])
  577. expect(lastRequest().data.taskIds).toEqual([1, 2, 3])
  578. })
  579. test('getTodayParentTasks sends POST', async () => {
  580. mockSuccess({ code: 200 })
  581. await api.getTodayParentTasks()
  582. expect(lastRequest().url).toMatch(/\/api\/tasks\/today-parent$/)
  583. })
  584. })
  585. // --------------- points module ---------------
  586. describe('points API', () => {
  587. test('getPointsBalance sends POST with memberId', async () => {
  588. mockSuccess({ code: 200 })
  589. await api.getPointsBalance(5)
  590. expect(lastRequest().data.memberId).toBe(5)
  591. })
  592. test('getPointsLogs sends POST with pagination', async () => {
  593. mockSuccess({ code: 200 })
  594. await api.getPointsLogs(5, 2, 20)
  595. expect(lastRequest().data.memberId).toBe(5)
  596. expect(lastRequest().data.page).toBe(2)
  597. expect(lastRequest().data.size).toBe(20)
  598. })
  599. })
  600. // --------------- rewards / wishes module ---------------
  601. describe('rewards & wishes API', () => {
  602. test('createReward sends POST', async () => {
  603. mockSuccess({ code: 200 })
  604. await api.createReward({ name: '玩具', points: 100 })
  605. expect(lastRequest().data.name).toBe('玩具')
  606. })
  607. test('getWishlist sends POST with memberId', async () => {
  608. mockSuccess({ code: 200 })
  609. await api.getWishlist(5)
  610. expect(lastRequest().data.memberId).toBe(5)
  611. })
  612. test('exchangeReward sends POST', async () => {
  613. mockSuccess({ code: 200 })
  614. await api.exchangeReward(1, 5)
  615. expect(lastRequest().data.memberId).toBe(5)
  616. })
  617. test('getPendingWishes sends POST with empty body', async () => {
  618. mockSuccess({ code: 200 })
  619. await api.getPendingWishes()
  620. expect(lastRequest().data).toEqual({})
  621. })
  622. test('getWishes sends POST with params', async () => {
  623. mockSuccess({ code: 200 })
  624. await api.getWishes({ memberId: 5, status: 'pending' })
  625. expect(lastRequest().data.memberId).toBe(5)
  626. })
  627. test('setWishPrice sends POST with pointsRequired', async () => {
  628. mockSuccess({ code: 200 })
  629. await api.setWishPrice(1, 200)
  630. expect(lastRequest().data.pointsRequired).toBe(200)
  631. })
  632. test('approveWishExchange sends POST', async () => {
  633. mockSuccess({ code: 200 })
  634. await api.approveWishExchange(1, true)
  635. expect(lastRequest().data.approved).toBe(true)
  636. })
  637. test('createWish sends POST with data', async () => {
  638. mockSuccess({ code: 200 })
  639. await api.createWish({ title: '新书包', memberId: 5 })
  640. expect(lastRequest().data.title).toBe('新书包')
  641. })
  642. })
  643. // --------------- identity parameter hardening ---------------
  644. // 前端不再向后端发送可伪造的 userId / familyId / childId(仅 memberId),
  645. // 身份一律由后端从 JWT 推导。以下断言锁定这一不变量。
  646. describe('identity parameter hardening', () => {
  647. beforeEach(() => {
  648. global.uni._storage.token = 'test-token'
  649. })
  650. test('request() does NOT send X-User-Id header', async () => {
  651. mockSuccess({ code: 200 })
  652. await api.getPendingWishes()
  653. const opts = lastRequest()
  654. expect(opts.header['X-User-Id']).toBeUndefined()
  655. })
  656. test('getMyAssessmentResults sends empty body, no userId', async () => {
  657. mockSuccess({ code: 200 })
  658. await api.getMyAssessmentResults()
  659. const opts = lastRequest()
  660. expect(opts.data).toEqual({})
  661. expect(opts.data.userId).toBeUndefined()
  662. })
  663. test('getChildAssessmentResults sends empty body, no userId', async () => {
  664. mockSuccess({ code: 200 })
  665. await api.getChildAssessmentResults()
  666. const opts = lastRequest()
  667. expect(opts.data).toEqual({})
  668. expect(opts.data.userId).toBeUndefined()
  669. })
  670. test('getTodayTasksByCategory sends only memberId and category', async () => {
  671. mockSuccess({ code: 200 })
  672. await api.getTodayTasksByCategory(7, 'wisdom')
  673. const opts = lastRequest()
  674. expect(opts.data.memberId).toBe(7)
  675. expect(opts.data.category).toBe('wisdom')
  676. expect(opts.data.childId).toBeUndefined()
  677. expect(opts.data.userId).toBeUndefined()
  678. })
  679. })
  680. // --------------- guide / packages module ---------------
  681. describe('guide & packages API', () => {
  682. test('getGuidePackages sends POST to my list', async () => {
  683. mockSuccess({ code: 200 })
  684. await api.getGuidePackages(1)
  685. expect(lastRequest().url).toMatch(/\/api\/guide\/packages\/my$/)
  686. expect(lastRequest().data.guideId).toBe(1)
  687. })
  688. test('registerGuide sends POST', async () => {
  689. mockSuccess({ code: 200 })
  690. await api.registerGuide({ name: '张老师', level: 'senior' })
  691. expect(lastRequest().url).toMatch(/\/api\/guide\/register$/)
  692. })
  693. test('generateBindInvite sends POST', async () => {
  694. mockSuccess({ code: 200 })
  695. await api.generateBindInvite()
  696. expect(lastRequest().url).toMatch(/\/api\/guide\/bind\/invite$/)
  697. })
  698. test('getBoundFamilies sends POST', async () => {
  699. mockSuccess({ code: 200 })
  700. await api.getBoundFamilies()
  701. expect(lastRequest().url).toMatch(/\/api\/guide\/families$/)
  702. })
  703. test('getTeamMembers sends POST', async () => {
  704. mockSuccess({ code: 200 })
  705. await api.getTeamMembers()
  706. expect(lastRequest().url).toMatch(/\/api\/guide\/team\/members$/)
  707. })
  708. test('getGuideOrders sends POST', async () => {
  709. mockSuccess({ code: 200 })
  710. await api.getGuideOrders()
  711. expect(lastRequest().url).toMatch(/\/api\/guide\/orders\/list$/)
  712. })
  713. test('getGuideMessages sends POST', async () => {
  714. mockSuccess({ code: 200 })
  715. await api.getGuideMessages()
  716. expect(lastRequest().url).toMatch(/\/api\/guide\/messages\/list$/)
  717. })
  718. })
  719. // --------------- payment module ---------------
  720. describe('payment API', () => {
  721. test('createWechatPayOrder sends POST', async () => {
  722. mockSuccess({ code: 200 })
  723. await api.createWechatPayOrder('NO001', '测试订单', 100)
  724. expect(lastRequest().data.orderNo).toBe('NO001')
  725. expect(lastRequest().data.amount).toBe(100)
  726. })
  727. })
  728. // --------------- assessment module ---------------
  729. describe('assessment API', () => {
  730. test('createAssessmentAppointment sends POST', async () => {
  731. mockSuccess({ code: 200 })
  732. await api.createAssessmentAppointment({ memberId: 5, date: '2026-06-20' })
  733. expect(lastRequest().url).toMatch(/\/api\/dan-assessment\/appointment\/create$/)
  734. })
  735. test('payAssessmentOrder sends POST', async () => {
  736. mockSuccess({ code: 200 })
  737. await api.payAssessmentOrder('ORDER001', 'wechat')
  738. expect(lastRequest().data.orderNo).toBe('ORDER001')
  739. })
  740. test('recordAssessmentResult sends POST', async () => {
  741. mockSuccess({ code: 200 })
  742. await api.recordAssessmentResult({ orderId: 1, score: 85 })
  743. expect(lastRequest().url).toMatch(/\/api\/dan-assessment\/result\/record$/)
  744. })
  745. })
  746. // --------------- mini-games module ---------------
  747. describe('mini-games API', () => {
  748. test('getMiniGameList sends POST', async () => {
  749. mockSuccess({ code: 200 })
  750. await api.getMiniGameList()
  751. expect(lastRequest().url).toMatch(/\/api\/mini-game\/list$/)
  752. })
  753. test('getMiniGameByCode sends POST', async () => {
  754. mockSuccess({ code: 200 })
  755. await api.getMiniGameByCode('sudoku')
  756. expect(lastRequest().url).toMatch(/\/api\/mini-game\/sudoku$/)
  757. })
  758. test('completeMiniGame sends POST with game data', async () => {
  759. mockSuccess({ code: 200 })
  760. await api.completeMiniGame(5, 'sudoku', 120, 85)
  761. expect(lastRequest().data.memberId).toBe(5)
  762. expect(lastRequest().data.gameCode).toBe('sudoku')
  763. expect(lastRequest().data.completionTime).toBe(120)
  764. expect(lastRequest().data.score).toBe(85)
  765. })
  766. test('getGameHistory sends POST', async () => {
  767. mockSuccess({ code: 200 })
  768. await api.getGameHistory({ memberId: 5 })
  769. expect(lastRequest().url).toMatch(/\/api\/game\/history$/)
  770. })
  771. test('getGameLeaderboard sends POST', async () => {
  772. mockSuccess({ code: 200 })
  773. await api.getGameLeaderboard({ gameCode: 'sudoku' })
  774. expect(lastRequest().url).toMatch(/\/api\/game\/leaderboard$/)
  775. })
  776. })
  777. // --------------- growth module ---------------
  778. describe('growth records API', () => {
  779. test('createGrowthRecord sends POST', async () => {
  780. mockSuccess({ code: 200 })
  781. await api.createGrowthRecord({ memberId: 5, content: '长高了2cm' })
  782. expect(lastRequest().url).toMatch(/\/api\/growth\/record\/create$/)
  783. })
  784. test('getGrowthRecordList sends POST', async () => {
  785. mockSuccess({ code: 200 })
  786. await api.getGrowthRecordList()
  787. expect(lastRequest().url).toMatch(/\/api\/growth\/record\/list$/)
  788. })
  789. test('createGrowthRecord with alsoPurchaseAssessment uses merge endpoint', async () => {
  790. mockSuccess({ code: 200 })
  791. await api.createGrowthRecord({ memberId: 5, alsoPurchaseAssessment: true })
  792. expect(lastRequest().url).toMatch(/\/api\/growth\/record\/create-with-order$/)
  793. })
  794. })
  795. // --------------- energy module ---------------
  796. describe('energy API', () => {
  797. test('getEnergyOverview sends POST with memberId', async () => {
  798. mockSuccess({ code: 200 })
  799. await api.getEnergyOverview(5)
  800. expect(lastRequest().data.memberId).toBe(5)
  801. })
  802. test('getEnergyLogs sends POST', async () => {
  803. mockSuccess({ code: 200 })
  804. await api.getEnergyLogs(5, 'body', 1, 20)
  805. expect(lastRequest().data.dimensionCode).toBe('body')
  806. })
  807. test('getFamilyEnergySandbox sends POST', async () => {
  808. mockSuccess({ code: 200 })
  809. await api.getFamilyEnergySandbox()
  810. expect(lastRequest().url).toMatch(/\/api\/energy\/sandbox$/)
  811. })
  812. })
  813. // --------------- badges module ---------------
  814. describe('badges API', () => {
  815. test('getActiveBadges sends POST', async () => {
  816. mockSuccess({ code: 200 })
  817. await api.getActiveBadges()
  818. expect(lastRequest().url).toMatch(/\/api\/badges\/list$/)
  819. })
  820. test('getChildBadges sends POST with memberId', async () => {
  821. mockSuccess({ code: 200 })
  822. await api.getChildBadges(5)
  823. expect(lastRequest().data.memberId).toBe(5)
  824. })
  825. test('toggleBadgeFavorite sends POST', async () => {
  826. mockSuccess({ code: 200 })
  827. await api.toggleBadgeFavorite(5, 3)
  828. expect(lastRequest().data.memberId).toBe(5)
  829. expect(lastRequest().data.badgeId).toBe(3)
  830. })
  831. })
  832. // --------------- articles module ---------------
  833. describe('articles API', () => {
  834. test('getArticleCategories sends POST', async () => {
  835. mockSuccess({ code: 200 })
  836. await api.getArticleCategories()
  837. expect(lastRequest().url).toMatch(/\/api\/articles\/categories$/)
  838. })
  839. test('getArticleList sends POST with data', async () => {
  840. mockSuccess({ code: 200 })
  841. await api.getArticleList({ categoryId: 1, page: 1 })
  842. expect(lastRequest().url).toMatch(/\/api\/articles\/list$/)
  843. })
  844. test('getArticleDetail sends POST', async () => {
  845. mockSuccess({ code: 200 })
  846. await api.getArticleDetail({ id: 42 })
  847. expect(lastRequest().url).toMatch(/\/api\/articles\/detail$/)
  848. })
  849. test('getDailyTip sends POST', async () => {
  850. mockSuccess({ code: 200 })
  851. await api.getDailyTip()
  852. expect(lastRequest().url).toMatch(/\/api\/articles\/daily-tip$/)
  853. })
  854. })
  855. // --------------- contact module ---------------
  856. describe('contact API', () => {
  857. test('getContactList sends POST', async () => {
  858. mockSuccess({ code: 200 })
  859. await api.getContactList({ memberId: 5 })
  860. expect(lastRequest().url).toMatch(/\/api\/contact\/list$/)
  861. })
  862. test('createContact sends POST with data', async () => {
  863. mockSuccess({ code: 200 })
  864. await api.createContact({ name: '爷爷', relation: 'grandfather' })
  865. expect(lastRequest().url).toMatch(/\/api\/contact\/create$/)
  866. })
  867. test('deleteContact sends POST with id', async () => {
  868. mockSuccess({ code: 200 })
  869. await api.deleteContact(3)
  870. expect(lastRequest().url).toMatch(/\/api\/contact\/delete$/)
  871. expect(lastRequest().data.id).toBe(3)
  872. })
  873. test('importPhoneContact sends POST', async () => {
  874. mockSuccess({ code: 200 })
  875. await api.importPhoneContact({ contacts: [{ name: '张三', phone: '13800138000' }] })
  876. expect(lastRequest().url).toMatch(/\/api\/contact\/import-phone$/)
  877. })
  878. })
  879. // --------------- vendor module ---------------
  880. describe('vendor API', () => {
  881. test('vendorApply sends POST with data', async () => {
  882. mockSuccess({ code: 200 })
  883. await api.vendorApply({ companyName: '某某公司', type: 'planner' })
  884. expect(lastRequest().url).toMatch(/\/api\/vendor\/apply$/)
  885. })
  886. test('vendorStatus sends POST', async () => {
  887. mockSuccess({ code: 200 })
  888. await api.vendorStatus()
  889. expect(lastRequest().url).toMatch(/\/api\/vendor\/status$/)
  890. })
  891. test('vendorInfo sends POST', async () => {
  892. mockSuccess({ code: 200 })
  893. await api.vendorInfo()
  894. expect(lastRequest().url).toMatch(/\/api\/vendor\/info$/)
  895. })
  896. })
  897. // --------------- product module ---------------
  898. describe('product API', () => {
  899. test('productList sends POST', () => {
  900. // productList uses new Promise without success/fail callbacks,
  901. // so we check the request synchronously.
  902. api.productList({ page: 1, size: 10 })
  903. const opts = lastRequest()
  904. expect(opts.method).toBe('POST')
  905. expect(opts.url).toMatch(/\/api\/product\/list$/)
  906. })
  907. test('productDetail sends POST', async () => {
  908. mockSuccess({ code: 200 })
  909. await api.productDetail({ id: 1 })
  910. expect(lastRequest().url).toMatch(/\/api\/product\/detail$/)
  911. })
  912. test('productCreate sends POST', async () => {
  913. mockSuccess({ code: 200 })
  914. await api.productCreate({ name: '测试商品', price: 100 })
  915. expect(lastRequest().url).toMatch(/\/api\/product\/create$/)
  916. })
  917. test('productOrderCreate sends POST', async () => {
  918. mockSuccess({ code: 200 })
  919. await api.productOrderCreate({ productId: 1, quantity: 2 })
  920. expect(lastRequest().url).toMatch(/\/api\/product\/order\/create$/)
  921. })
  922. })
  923. // --------------- commission / invite ---------------
  924. describe('commission & invite API', () => {
  925. test('getReferralCode sends POST', async () => {
  926. mockSuccess({ code: 200 })
  927. await api.getReferralCode()
  928. expect(lastRequest().url).toMatch(/\/api\/invite\/code$/)
  929. })
  930. test('bindReferral sends POST with code', async () => {
  931. mockSuccess({ code: 200 })
  932. await api.bindReferral('ABC123')
  933. expect(lastRequest().data.referralCode).toBe('ABC123')
  934. })
  935. test('getCommissionSummary sends POST', async () => {
  936. mockSuccess({ code: 200 })
  937. await api.getCommissionSummary()
  938. expect(lastRequest().url).toMatch(/\/api\/commission\/summary$/)
  939. })
  940. test('applyWithdrawal sends POST', async () => {
  941. mockSuccess({ code: 200 })
  942. await api.applyWithdrawal(500, { bank: 'ICBC', account: '6222****' })
  943. expect(lastRequest().data.amount).toBe(500)
  944. })
  945. })
  946. // --------------- stats module ---------------
  947. describe('stats API', () => {
  948. test('getChildCompletionStats sends POST', async () => {
  949. mockSuccess({ code: 200 })
  950. await api.getChildCompletionStats({ memberId: 5 })
  951. expect(lastRequest().url).toMatch(/\/api\/stats\/child-completion$/)
  952. })
  953. test('getChildOverview sends POST with memberId', async () => {
  954. mockSuccess({ code: 200 })
  955. await api.getChildOverview(5)
  956. expect(lastRequest().data.memberId).toBe(5)
  957. })
  958. })
  959. // --------------- AI chat module ---------------
  960. describe('AI chat API', () => {
  961. test('aiSendMessage sends POST', async () => {
  962. mockSuccess({ code: 200 })
  963. await api.aiSendMessage({ conversationId: 1, content: '你好' })
  964. expect(lastRequest().url).toMatch(/\/api\/ai\/chat\/send$/)
  965. })
  966. test('aiGetConversations sends POST', async () => {
  967. mockSuccess({ code: 200 })
  968. await api.aiGetConversations()
  969. expect(lastRequest().url).toMatch(/\/api\/ai\/chat\/conversations$/)
  970. })
  971. })
  972. // --------------- health / wealth module ---------------
  973. // --------------- health report module (new) ---------------
  974. describe('health report API', () => {
  975. test('createHealthReport sends POST', async () => {
  976. mockSuccess({ code: 200 })
  977. await api.createHealthReport({ memberId: 5, reportData: { height: 120, weight: 22 } })
  978. expect(lastRequest().url).toMatch(/\/api\/health\/report\/create$/)
  979. expect(lastRequest().data.memberId).toBe(5)
  980. })
  981. test('getReportList sends POST with memberId', async () => {
  982. mockSuccess({ code: 200 })
  983. await api.getReportList(5)
  984. expect(lastRequest().url).toMatch(/\/api\/health\/report\/list$/)
  985. expect(lastRequest().data.memberId).toBe(5)
  986. })
  987. test('getReportDetail sends POST with reportId', async () => {
  988. mockSuccess({ code: 200 })
  989. await api.getReportDetail(42)
  990. expect(lastRequest().url).toMatch(/\/api\/health\/report\/detail$/)
  991. expect(lastRequest().data.reportId).toBe(42)
  992. })
  993. test('getLatestHealthReport sends POST with memberId', async () => {
  994. mockSuccess({ code: 200 })
  995. await api.getLatestHealthReport(5)
  996. expect(lastRequest().url).toMatch(/\/api\/health\/report\/latest$/)
  997. expect(lastRequest().data.memberId).toBe(5)
  998. })
  999. test('getHealthIndicatorList sends POST with memberId', async () => {
  1000. mockSuccess({ code: 200 })
  1001. await api.getHealthIndicatorList(5)
  1002. expect(lastRequest().url).toMatch(/\/api\/health\/indicator\/list$/)
  1003. expect(lastRequest().data.memberId).toBe(5)
  1004. })
  1005. test('createReportSurvey sends POST with reportId and memberId', async () => {
  1006. mockSuccess({ code: 200 })
  1007. await api.createReportSurvey(10, 5)
  1008. expect(lastRequest().url).toMatch(/\/api\/health\/survey\/create$/)
  1009. expect(lastRequest().data.reportId).toBe(10)
  1010. expect(lastRequest().data.memberId).toBe(5)
  1011. })
  1012. test('submitReportSurvey sends POST with surveyId and data', async () => {
  1013. mockSuccess({ code: 200 })
  1014. await api.submitReportSurvey(1, { q1: 'yes', q2: 'no' })
  1015. expect(lastRequest().url).toMatch(/\/api\/health\/survey\/submit$/)
  1016. expect(lastRequest().data.surveyId).toBe(1)
  1017. expect(lastRequest().data.surveyData.q1).toBe('yes')
  1018. })
  1019. test('getSurveyStatus sends POST with reportId', async () => {
  1020. mockSuccess({ code: 200 })
  1021. await api.getSurveyStatus({ reportId: 10 })
  1022. expect(lastRequest().url).toMatch(/\/api\/survey\/status$/)
  1023. expect(lastRequest().data.reportId).toBe(10)
  1024. })
  1025. })
  1026. describe('health & wealth API', () => {
  1027. test('healthCheckinList sends POST', async () => {
  1028. mockSuccess({ code: 200 })
  1029. await api.healthCheckinList({ memberId: 5 })
  1030. expect(lastRequest().url).toMatch(/\/api\/health\/checkin\/list$/)
  1031. })
  1032. test('getCheckinList sends POST', async () => {
  1033. mockSuccess({ code: 200 })
  1034. await api.getCheckinList({ memberId: 5 })
  1035. expect(lastRequest().url).toMatch(/\/api\/wealth\/checkin\/list$/)
  1036. })
  1037. test('getInsuranceList sends POST', async () => {
  1038. mockSuccess({ code: 200 })
  1039. await api.getInsuranceList({ memberId: 5 })
  1040. expect(lastRequest().url).toMatch(/\/api\/wealth\/insurance\/list$/)
  1041. })
  1042. })
  1043. // --------------- invite card module ---------------
  1044. describe('invite card API', () => {
  1045. test('generateInviteCard sends POST', async () => {
  1046. mockSuccess({ code: 200 })
  1047. await api.generateInviteCard('guide', 1)
  1048. expect(lastRequest().data.type).toBe('guide')
  1049. })
  1050. test('verifyInviteCard sends POST with code', async () => {
  1051. mockSuccess({ code: 200 })
  1052. await api.verifyInviteCard('CARD123')
  1053. expect(lastRequest().data.code).toBe('CARD123')
  1054. })
  1055. })