| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235 |
- /**
- * Tests for cfc-frontend utils/api.js
- *
- * Mocks uni.request to intercept and verify API calls.
- */
- import * as api from '@/utils/api'
- // --------------- helpers ---------------
- /** Helper: make uni.request call success(data) on next tick */
- function mockSuccess(data) {
- global.uni.request.mockImplementation((opts) => {
- process.nextTick(() => {
- if (opts.success) opts.success({ data })
- })
- })
- }
- /** Helper: make uni.request call fail(err) on next tick */
- function mockFail(err) {
- global.uni.request.mockImplementation((opts) => {
- process.nextTick(() => {
- if (opts.fail) opts.fail(err)
- })
- })
- }
- function mockSequence(responses) {
- var i = 0
- global.uni.request.mockImplementation((opts) => {
- var resp = responses[Math.min(i, responses.length - 1)]
- i++
- process.nextTick(() => {
- if (resp.err) {
- if (opts.fail) opts.fail(resp.err)
- } else {
- if (opts.success) opts.success({ data: resp.data })
- }
- })
- })
- }
- // --------------- global beforeEach ---------------
- beforeEach(() => {
- global.uni._storage = {}
- global.uni.request.mockReset()
- global.uni.showToast.mockReset()
- global.uni.reLaunch.mockReset()
- global.uni.login.mockReset()
- global.getCurrentPages.mockReset()
- global.getCurrentPages.mockReturnValue([{ route: 'pages/index-home/index' }])
- global.uni.getAccountInfoSync.mockReset()
- global.uni.getAccountInfoSync.mockReturnValue({
- miniProgram: { envVersion: 'develop' }
- })
- // api.js 的 3 秒请求去重缓存是模块级单例,跨用例残留会让后续用例拿到上一个用例缓存的
- // Promise(同 URL+method+body),表现为「本该 401 却是 200」「lastRequest() 为 undefined」。
- // 每个用例前显式清空,保证用例间隔离。
- api.clearApiDedup()
- })
- /** Capture the last uni.request call options */
- function lastRequest() {
- const calls = global.uni.request.mock.calls
- return calls[calls.length - 1][0]
- }
- // --------------- auth module ---------------
- describe('auth API', () => {
- beforeEach(() => {
- global.uni._storage.token = 'test-token'
- global.uni._storage.userId = '42'
- })
- test('wechatLogin sends POST /api/auth/wechat-login', async () => {
- mockSuccess({ code: 200, data: { token: 'jwt' } })
- const res = await api.wechatLogin('code123', { nickname: 'test' })
- const opts = lastRequest()
- expect(opts.method).toBe('POST')
- expect(opts.url).toMatch(/\/api\/auth\/wechat-login$/)
- expect(opts.data.code).toBe('code123')
- expect(res.data.token).toBe('jwt')
- })
- test('phoneLogin sends POST with phone and code', async () => {
- mockSuccess({ code: 200, data: { token: 'jwt' } })
- await api.phoneLogin({ phone: '13800138000', code: '1234' })
- const opts = lastRequest()
- expect(opts.method).toBe('POST')
- expect(opts.url).toMatch(/\/api\/auth\/phone-login$/)
- expect(opts.data.phone).toBe('13800138000')
- })
- test('sendCode sends POST with data', async () => {
- mockSuccess({ code: 200 })
- await api.sendCode({ phone: '13800138000' })
- const opts = lastRequest()
- expect(opts.method).toBe('POST')
- expect(opts.url).toMatch(/\/api\/auth\/send-code$/)
- })
- test('silentLogin sends POST with code', async () => {
- mockSuccess({ code: 200 })
- await api.silentLogin('wxcode')
- expect(lastRequest().data.code).toBe('wxcode')
- })
- // 已废弃:后端 /api/auth/auto-login 已改为 410 Gone(裸 openid 换 token 属越权漏洞)。
- // 导出仅为排查历史调用保留,不得在新代码中使用;续期请走 silentRelogin()。
- test('autoLogin (deprecated) still targets /api/auth/auto-login', async () => {
- mockSuccess({ code: 410, message: '该接口已废弃,请改用 /api/auth/silent-login' })
- await expect(api.autoLogin('openid_xxx')).rejects.toEqual(
- { code: 410, message: '该接口已废弃,请改用 /api/auth/silent-login' }
- )
- const opts = lastRequest()
- expect(opts.url).toMatch(/\/api\/auth\/auto-login$/)
- expect(opts.data.openid).toBe('openid_xxx')
- })
- test('setPassword and verifyPassword send correct endpoints', async () => {
- mockSuccess({ code: 200 })
- await api.setPassword('secret')
- expect(lastRequest().url).toMatch(/\/api\/auth\/set-password$/)
- expect(lastRequest().data.password).toBe('secret')
- await api.verifyPassword('secret')
- expect(lastRequest().url).toMatch(/\/api\/auth\/verify-password$/)
- })
- test('directRegister sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.directRegister({ phone: '13800138000', nickname: 'tester' })
- expect(lastRequest().url).toMatch(/\/api\/auth\/direct-register$/)
- })
- test('checkPhone sends POST with phone', async () => {
- mockSuccess({ code: 200 })
- await api.checkPhone('13800138000')
- expect(lastRequest().data.phone).toBe('13800138000')
- })
- test('wechatPhoneLogin sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.wechatPhoneLogin({ code: 'wxcode', iv: 'iv', encryptedData: 'enc' })
- expect(lastRequest().url).toMatch(/\/api\/auth\/wechat-phone-login$/)
- })
- test('verifyToken sends POST /api/auth/verify with bearer token', async () => {
- mockSuccess({ code: 200, data: { userId: 42, role: 'parent' } })
- const res = await api.verifyToken()
- const opts = lastRequest()
- expect(opts.method).toBe('POST')
- expect(opts.url).toMatch(/\/api\/auth\/verify$/)
- expect(opts.header.Authorization).toBe('Bearer test-token')
- expect(res.data.userId).toBe(42)
- })
- test('verifyToken with 401 (token expired) clears auth and redirects to login', async () => {
- jest.useFakeTimers()
- mockSuccess({ code: 401, message: 'Token无效或已过期', data: null })
- await expect(api.verifyToken()).rejects.toEqual({ code: 401, message: 'Token无效或已过期', data: null })
- expect(global.uni._storage.token).toBeUndefined()
- // 触发 _clearAuthAndRedirect 内 1.5s setTimeout(reLaunch 在此定时器回调中执行)
- jest.runAllTimers()
- expect(global.uni.reLaunch).toHaveBeenCalledWith({ url: '/pages/login/login' })
- expect(global.uni.showToast).toHaveBeenCalled()
- jest.useRealTimers()
- })
- test('verifyToken with 401 (user deleted) clears auth and redirects to login', async () => {
- jest.useFakeTimers()
- mockSuccess({ code: 401, message: '用户不存在', data: null })
- await expect(api.verifyToken()).rejects.toEqual({ code: 401, message: '用户不存在', data: null })
- expect(global.uni._storage.token).toBeUndefined()
- jest.runAllTimers()
- expect(global.uni.reLaunch).toHaveBeenCalledWith({ url: '/pages/login/login' })
- expect(global.uni.showToast).toHaveBeenCalled()
- jest.useRealTimers()
- })
- // 静默续期 = uni.login() 取微信签发的一次性 code → /api/auth/silent-login(服务端 code2Session)。
- // 本地 openid 只作为「本设备曾登录过」的触发条件,不作为凭证上送。
- function mockUniLoginCode(code) {
- global.uni.login.mockImplementation((opts) => {
- process.nextTick(() => {
- if (opts.success) opts.success({ code: code || 'wxcode' })
- })
- })
- }
- test('401 silently re-logins via wx.login + code2Session and retries original request', async () => {
- global.uni.reLaunch.mockReset()
- global.uni.showToast.mockReset()
- global.uni._storage.openid = 'openid_abc'
- global.uni._storage.token = 'expired-token'
- mockUniLoginCode('fresh-wxcode')
- mockSequence([
- { data: { code: 401, message: 'Token无效或已过期', data: null } },
- { data: { code: 200, data: { token: 'new-jwt', userId: 42, role: 'parent', familyId: 1, openid: 'openid_abc' } } },
- { data: { code: 200, data: { userId: 42, role: 'parent' } } }
- ])
- const res = await api.verifyToken()
- expect(res.data.userId).toBe(42)
- expect(global.uni._storage.token).toBe('new-jwt')
- // 续期必须走 code2Session,且不得把 openid 当凭证发送
- const calls = global.uni.request.mock.calls.map((c) => c[0])
- const renewReq = calls.find((c) => /\/api\/auth\/silent-login/.test(c.url))
- expect(renewReq).toBeDefined()
- expect(renewReq.data.code).toBe('fresh-wxcode')
- expect(renewReq.data.openid).toBeUndefined()
- // 已废弃的裸 openid 换 token 接口不得被调用
- expect(calls.find((c) => /\/api\/auth\/auto-login/.test(c.url))).toBeUndefined()
- expect(global.uni.reLaunch).not.toHaveBeenCalled()
- expect(global.uni.showToast).not.toHaveBeenCalled()
- })
- // 回归:首页冷启动会并发打出多个 401(family/member/list、membership/my、onboarding/progress…)。
- // 修复前 _handle401 在 _reloginLock 为真时直接调 _clearAuthAndRedirect():
- // 第 1 个 401 刚启动 silentRelogin()(uni.login 异步),第 2、3 个 401 立刻把 token 从
- // storage 抹掉并预约 1500ms 后 reLaunch 登录页 → 在途续期被打断,
- // 线上表现为「控制台只有 401、没有任何续期日志、用户被弹回登录页」。
- test('concurrent 401s queue behind one renewal and all get replayed', async () => {
- global.uni._storage.openid = 'openid_abc'
- global.uni._storage.token = 'expired-token'
- mockUniLoginCode('fresh-wxcode')
- // 3 个业务请求同时 401 → 续期 1 次成功 → 3 个重放全部 200
- mockSequence([
- { data: { code: 401, message: 'Token无效或已过期', data: null } },
- { data: { code: 401, message: 'Token无效或已过期', data: null } },
- { data: { code: 401, message: 'Token无效或已过期', data: null } },
- { data: { code: 200, data: { token: 'new-jwt', userId: 42, role: 'parent', familyId: 1, openid: 'openid_abc' } } },
- { data: { code: 200, data: { ok: 'verify' } } },
- { data: { code: 200, data: { ok: 'members' } } },
- { data: { code: 200, data: { ok: 'membership' } } }
- ])
- const [verifyRes, memberRes, membershipRes] = await Promise.all([
- api.verifyToken(),
- api.getFamilyMemberList({}),
- api.getMyMembership()
- ])
- // 三个请求都必须拿到成功结果(修复前后两个会被 reject)
- expect(verifyRes.data.ok).toBe('verify')
- expect(memberRes.data.ok).toBe('members')
- expect(membershipRes.data.ok).toBe('membership')
- const calls = global.uni.request.mock.calls.map((c) => c[0])
- // 续期只发生一次,绝不能因并发 401 引发续期风暴
- expect(calls.filter((c) => /\/api\/auth\/silent-login/.test(c.url)).length).toBe(1)
- // token 必须是被续期后的新值,而不是被并发 401 抹掉
- expect(global.uni._storage.token).toBe('new-jwt')
- // 关键回归点:并发 401 不得触发「登录已过期」提示,也不得跳登录页
- expect(global.uni.showToast).not.toHaveBeenCalled()
- expect(global.uni.reLaunch).not.toHaveBeenCalled()
- })
- // 回归:重放请求若仍 401(刚签发的 token 依旧不可用),必须直接失败而不是重新入队,
- // 否则「续期 → 重放 → 401 → 续期 → 重放」会 ping-pong 死循环。
- test('replayed request that still 401 fails without triggering another renewal', async () => {
- global.uni._storage.openid = 'openid_abc'
- global.uni._storage.token = 'expired-token'
- mockUniLoginCode('fresh-wxcode')
- mockSequence([
- { data: { code: 401, message: 'Token无效或已过期', data: null } },
- { data: { code: 200, data: { token: 'new-jwt', userId: 42, role: 'parent', familyId: 1, openid: 'openid_abc' } } },
- { data: { code: 401, message: 'Token无效或已过期', data: null } }
- ])
- await expect(api.verifyToken()).rejects.toEqual({ code: 401, message: 'Token无效或已过期', data: null })
- const calls = global.uni.request.mock.calls.map((c) => c[0])
- // 只续期过一次,重放 401 不再触发第二次续期
- expect(calls.filter((c) => /\/api\/auth\/silent-login/.test(c.url)).length).toBe(1)
- expect(global.uni._storage.token).toBe('new-jwt')
- })
- test('401 retry does not duplicate query params in the replayed request URL', async () => {
- global.uni._storage.openid = 'openid_abc'
- global.uni._storage.token = 'expired-token'
- mockUniLoginCode('fresh-wxcode')
- mockSequence([
- { data: { code: 401, message: 'Token无效或已过期', data: null } },
- { data: { code: 200, data: { token: 'new-jwt', userId: 42, role: 'parent', familyId: 1, openid: 'openid_abc' } } },
- { data: { code: 200, data: { ok: true } } }
- ])
- // publishPackage 通过 options 传 query(?publish=true),是最容易暴露重复拼接的调用形态
- await api.publishPackage(7, true)
- const calls = global.uni.request.mock.calls.map((c) => c[0])
- const hits = calls.filter((c) => /\/api\/packages\/7\/publish/.test(c.url))
- expect(hits.length).toBe(2) // 原始请求 1 次 + 401 续期后重放 1 次
- // 修复前:_handle401 收到的是已拼过 query 的 url,重放时 options 又拼一次 → ?publish=true&publish=true
- hits.forEach((c) => {
- expect(c.url).toBe(c.url.split('?')[0] + '?publish=true')
- expect((c.url.match(/publish=/g) || []).length).toBe(1)
- })
- })
- test('401 during app launch window clears auth but does NOT navigate to login subpackage', async () => {
- jest.useFakeTimers()
- global.uni._storage.openid = 'openid_abc'
- global.uni._storage.token = 'expired-token'
- // 仍停在 splash:pages/login 是分包,此刻尚未下载,
- // reLaunch 过去会报 'Page "pages/login/login" has not been registered yet'
- global.getCurrentPages.mockReturnValue([{ route: 'pages/splash/index' }])
- mockUniLoginCode()
- mockSequence([
- { data: { code: 401, message: 'Token无效或已过期', data: null } },
- { data: { code: 500, message: '用户不存在,请先登录', data: null } }
- ])
- await expect(api.verifyToken()).rejects.toEqual({ code: 401, message: 'Token无效或已过期', data: null })
- jest.runAllTimers()
- // 登录态必须清掉
- expect(global.uni._storage.token).toBeUndefined()
- // 但启动窗口内绝不跳登录页,交由 splash 落地首页(主包)
- expect(global.uni.reLaunch).not.toHaveBeenCalled()
- jest.useRealTimers()
- })
- test('401 during app launch window (no page registered yet) also skips navigation', async () => {
- jest.useFakeTimers()
- global.uni._storage.openid = 'openid_abc'
- global.uni._storage.token = 'expired-token'
- // 首屏尚未注册,getCurrentPages() 为空
- global.getCurrentPages.mockReturnValue([])
- mockUniLoginCode()
- mockSequence([
- { data: { code: 401, message: 'Token无效或已过期', data: null } },
- { data: { code: 500, message: '用户不存在,请先登录', data: null } }
- ])
- await expect(api.verifyToken()).rejects.toEqual({ code: 401, message: 'Token无效或已过期', data: null })
- jest.runAllTimers()
- expect(global.uni._storage.token).toBeUndefined()
- expect(global.uni.reLaunch).not.toHaveBeenCalled()
- jest.useRealTimers()
- })
- test('401 falls back to login page when silent re-login is refused', async () => {
- jest.useFakeTimers()
- global.uni._storage.openid = 'openid_abc'
- global.uni._storage.token = 'expired-token'
- mockUniLoginCode()
- mockSequence([
- { data: { code: 401, message: 'Token无效或已过期', data: null } },
- { data: { code: 500, message: '用户不存在,请先登录', data: null } }
- ])
- await expect(api.verifyToken()).rejects.toEqual({ code: 401, message: 'Token无效或已过期', data: null })
- jest.runAllTimers()
- expect(global.uni.reLaunch).toHaveBeenCalledWith({ url: '/pages/login/login' })
- expect(global.uni.showToast).toHaveBeenCalled()
- jest.useRealTimers()
- })
- test('401 with no cached openid (never logged in on this device) goes straight to login', async () => {
- jest.useFakeTimers()
- global.uni._storage.token = 'expired-token'
- mockSequence([
- { data: { code: 401, message: 'Token无效或已过期', data: null } }
- ])
- await expect(api.verifyToken()).rejects.toEqual({ code: 401, message: 'Token无效或已过期', data: null })
- // 本设备从未登录过 → 不应调用 uni.login 浪费一次 code2Session
- expect(global.uni.login).not.toHaveBeenCalled()
- jest.runAllTimers()
- expect(global.uni.reLaunch).toHaveBeenCalledWith({ url: '/pages/login/login' })
- jest.useRealTimers()
- })
- test('silentRelogin returns null when wx.login yields no code', async () => {
- global.uni._storage.openid = 'openid_abc'
- global.uni.login.mockImplementation((opts) => {
- process.nextTick(() => { if (opts.success) opts.success({}) })
- })
- await expect(api.silentRelogin()).resolves.toBeNull()
- expect(global.uni.request).not.toHaveBeenCalled()
- })
- test('silentRelogin returns null when wx.login fails', async () => {
- global.uni._storage.openid = 'openid_abc'
- global.uni.login.mockImplementation((opts) => {
- process.nextTick(() => { if (opts.fail) opts.fail({ errMsg: 'login:fail' }) })
- })
- await expect(api.silentRelogin()).resolves.toBeNull()
- expect(global.uni.request).not.toHaveBeenCalled()
- })
- test('silentRelogin does not issue a renew request on 401 (no recursive renewal)', async () => {
- global.uni._storage.openid = 'openid_abc'
- global.uni._storage.token = 'expired-token'
- mockUniLoginCode()
- // 续期接口自身返回 401:必须直接失败,不能再触发一次 silentRelogin,否则会递归续期/误清登录态
- mockSuccess({ code: 401, message: 'Token无效或已过期', data: null })
- await expect(api.silentRelogin()).resolves.toBeNull()
- expect(global.uni.request.mock.calls.length).toBe(1)
- // 续期失败不得清空登录态(那是「主动登出」才做的事)
- expect(global.uni._storage.token).toBe('expired-token')
- expect(global.uni.reLaunch).not.toHaveBeenCalled()
- })
- test('Authorization header includes Bearer token', async () => {
- mockSuccess({ code: 200 })
- global.uni._storage.token = 'my-jwt-token'
- await api.getUserInfo()
- const opts = lastRequest()
- expect(opts.header.Authorization).toBe('Bearer my-jwt-token')
- })
- test('X-User-Id header is NOT sent (removed for security)', async () => {
- mockSuccess({ code: 200 })
- global.uni._storage.userId = '99'
- await api.getUserInfo()
- expect(lastRequest().header['X-User-Id']).toBeUndefined()
- })
- test('rejects on non-200 code', async () => {
- mockSuccess({ code: 400, message: 'Bad Request' })
- await expect(api.getUserInfo()).rejects.toEqual({ code: 400, message: 'Bad Request' })
- })
- test('rejects on network failure', async () => {
- mockFail(new Error('Network error'))
- await expect(api.getUserInfo()).rejects.toThrow('Network error')
- })
- })
- // --------------- streets module ---------------
- describe('street address API', () => {
- test('getProvinces sends POST to /api/streets/provinces', async () => {
- mockSuccess({ code: 200, data: [] })
- await api.getProvinces()
- expect(lastRequest().url).toMatch(/\/api\/streets\/provinces$/)
- })
- test('getStreetChildren sends POST with parentId', async () => {
- mockSuccess({ code: 200 })
- await api.getStreetChildren(110000)
- expect(lastRequest().url).toMatch(/\/api\/streets\/children\/110000$/)
- })
- test('getStreetById sends POST to correct URL', async () => {
- mockSuccess({ code: 200 })
- await api.getStreetById(110101)
- expect(lastRequest().url).toMatch(/\/api\/streets\/110101$/)
- })
- test('getStreetPath sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getStreetPath(110101)
- expect(lastRequest().url).toMatch(/\/api\/streets\/110101\/path$/)
- })
- test('searchStreet sends POST with keyword', async () => {
- mockSuccess({ code: 200 })
- await api.searchStreet('北京')
- expect(lastRequest().data.keyword).toBe('北京')
- })
- test('matchByStreet sends POST with streetId', async () => {
- mockSuccess({ code: 200 })
- await api.matchByStreet(110101)
- expect(lastRequest().url).toMatch(/\/110101\/match$/)
- })
- })
- // --------------- user / family module ---------------
- describe('user & family API', () => {
- test('getUserInfo sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getUserInfo()
- expect(lastRequest().url).toMatch(/\/api\/user\/info$/)
- })
- test('updateUserInfo sends POST with data', async () => {
- mockSuccess({ code: 200 })
- await api.updateUserInfo({ nickname: 'new-name' })
- expect(lastRequest().data.nickname).toBe('new-name')
- })
- test('joinFamily sends POST with inviteCode', async () => {
- mockSuccess({ code: 200 })
- await api.joinFamily('ABC123')
- expect(lastRequest().data.inviteCode).toBe('ABC123')
- })
- test('createFamily sends POST with name', async () => {
- mockSuccess({ code: 200 })
- await api.createFamily('幸福之家')
- expect(lastRequest().data.name).toBe('幸福之家')
- })
- test('getFamilyMemberList sends POST to unified endpoint', async () => {
- mockSuccess({ code: 200 })
- await api.getFamilyMemberList()
- expect(lastRequest().url).toMatch(/\/api\/family\/member\/list$/)
- })
- test('getFamilyMemberList sends visibleOnly param', async () => {
- mockSuccess({ code: 200 })
- await api.getFamilyMemberList({ visibleOnly: true })
- expect(lastRequest().url).toMatch(/\/api\/family\/member\/list$/)
- expect(lastRequest().data.visibleOnly).toBe(true)
- })
- test('getFamilyMemberList sends includeFamily param', async () => {
- mockSuccess({ code: 200 })
- await api.getFamilyMemberList({ includeFamily: true })
- expect(lastRequest().url).toMatch(/\/api\/family\/member\/list$/)
- expect(lastRequest().data.includeFamily).toBe(true)
- })
- test('updateMemberVisibility sends POST with params', async () => {
- mockSuccess({ code: 200 })
- await api.updateMemberVisibility(1, 'child', true)
- expect(lastRequest().data.memberId).toBe(1)
- expect(lastRequest().data.memberType).toBe('child')
- expect(lastRequest().data.showToFamily).toBe(true)
- })
- test('switchMode sends POST with mode', async () => {
- mockSuccess({ code: 200 })
- await api.switchMode('child')
- expect(lastRequest().data.mode).toBe('child')
- })
- test('switchToChild sends POST with memberId', async () => {
- mockSuccess({ code: 200 })
- await api.switchToChild(5)
- expect(lastRequest().data.memberId).toBe(5)
- })
- test('switchBackToParent sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.switchBackToParent()
- expect(lastRequest().url).toMatch(/\/api\/user\/switch-back-to-parent$/)
- })
- test('getChildren sends POST to unified member list', async () => {
- mockSuccess({ code: 200 })
- await api.getChildren()
- expect(lastRequest().url).toMatch(/\/api\/family\/member\/list$/)
- })
- test('createChild sends POST with data', async () => {
- mockSuccess({ code: 200 })
- await api.createChild({ name: '小宝', gender: 'male' })
- expect(lastRequest().url).toMatch(/\/api\/family\/user\/children$/)
- expect(lastRequest().data.name).toBe('小宝')
- })
- test('updateChild sends POST merged with memberId', async () => {
- mockSuccess({ code: 200 })
- await api.updateChild(5, { nickname: '大宝' })
- expect(lastRequest().data.memberId).toBe(5)
- expect(lastRequest().data.nickname).toBe('大宝')
- })
- test('kickFamilyMember sends POST with targetUserId', async () => {
- mockSuccess({ code: 200 })
- await api.kickFamilyMember(10)
- expect(lastRequest().data.targetUserId).toBe(10)
- })
- })
- // --------------- membership module ---------------
- describe('membership API', () => {
- test('getMembershipLevels sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getMembershipLevels()
- expect(lastRequest().url).toMatch(/\/api\/membership\/levels$/)
- })
- test('getMyMembership sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getMyMembership()
- expect(lastRequest().url).toMatch(/\/api\/membership\/my$/)
- })
- test('createOrder sends POST with levelCode and paymentType', async () => {
- mockSuccess({ code: 200 })
- await api.createOrder('vip', 'wechat')
- expect(lastRequest().data.levelCode).toBe('vip')
- expect(lastRequest().data.paymentType).toBe('wechat')
- })
- })
- // --------------- tasks module ---------------
- describe('tasks API', () => {
- test('createTask sends POST with data', async () => {
- mockSuccess({ code: 200 })
- await api.createTask({ title: '晨读', memberId: 5 })
- expect(lastRequest().url).toMatch(/\/api\/tasks$/)
- expect(lastRequest().data.title).toBe('晨读')
- })
- test('getTodayTasks sends POST with memberId', async () => {
- mockSuccess({ code: 200 })
- await api.getTodayTasks(5)
- expect(lastRequest().data.memberId).toBe(5)
- })
- test('getPendingReviewTasks sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getPendingReviewTasks()
- expect(lastRequest().url).toMatch(/\/api\/tasks\/pending-review$/)
- })
- test('approveTask sends POST with approved:true', async () => {
- mockSuccess({ code: 200 })
- await api.approveTask(10)
- expect(lastRequest().url).toMatch(/\/api\/tasks\/10\/review$/)
- expect(lastRequest().data.approved).toBe(true)
- })
- test('rejectTask sends POST with approved:false', async () => {
- mockSuccess({ code: 200 })
- await api.rejectTask(10)
- expect(lastRequest().data.approved).toBe(false)
- })
- test('completeTask sends POST with memberId and photoUrl', async () => {
- mockSuccess({ code: 200 })
- await api.completeTask(10, 5, 'http://photo.url')
- expect(lastRequest().data.memberId).toBe(5)
- expect(lastRequest().data.photoUrl).toBe('http://photo.url')
- })
- test('reviewTask sends POST with data', async () => {
- mockSuccess({ code: 200 })
- await api.reviewTask(10, { approved: true, comment: '很好' })
- expect(lastRequest().url).toMatch(/\/api\/tasks\/10\/review$/)
- expect(lastRequest().data.comment).toBe('很好')
- })
- test('getTaskHistory sends POST with pagination', async () => {
- mockSuccess({ code: 200 })
- await api.getTaskHistory(5, 1, 20)
- expect(lastRequest().data.memberId).toBe(5)
- expect(lastRequest().data.page).toBe(1)
- expect(lastRequest().data.size).toBe(20)
- })
- test('deleteTask sends POST with _method DELETE', async () => {
- mockSuccess({ code: 200 })
- await api.deleteTask(10)
- expect(lastRequest().method).toBe('POST')
- expect(lastRequest().url).toMatch(/\/api\/tasks\/10$/)
- expect(lastRequest().data._method).toBe('DELETE')
- })
- test('batchCompleteTasks sends POST with array', async () => {
- mockSuccess({ code: 200 })
- await api.batchCompleteTasks([1, 2, 3])
- expect(lastRequest().data.taskIds).toEqual([1, 2, 3])
- })
- test('getTodayParentTasks sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getTodayParentTasks()
- expect(lastRequest().url).toMatch(/\/api\/tasks\/today-parent$/)
- })
- })
- // --------------- points module ---------------
- describe('points API', () => {
- test('getPointsBalance sends POST with memberId', async () => {
- mockSuccess({ code: 200 })
- await api.getPointsBalance(5)
- expect(lastRequest().data.memberId).toBe(5)
- })
- test('getPointsLogs sends POST with pagination', async () => {
- mockSuccess({ code: 200 })
- await api.getPointsLogs(5, 2, 20)
- expect(lastRequest().data.memberId).toBe(5)
- expect(lastRequest().data.page).toBe(2)
- expect(lastRequest().data.size).toBe(20)
- })
- })
- // --------------- rewards / wishes module ---------------
- describe('rewards & wishes API', () => {
- test('createReward sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.createReward({ name: '玩具', points: 100 })
- expect(lastRequest().data.name).toBe('玩具')
- })
- test('getWishlist sends POST with memberId', async () => {
- mockSuccess({ code: 200 })
- await api.getWishlist(5)
- expect(lastRequest().data.memberId).toBe(5)
- })
- test('exchangeReward sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.exchangeReward(1, 5)
- expect(lastRequest().data.memberId).toBe(5)
- })
- test('getPendingWishes sends POST with empty body', async () => {
- mockSuccess({ code: 200 })
- await api.getPendingWishes()
- expect(lastRequest().data).toEqual({})
- })
- test('getWishes sends POST with params', async () => {
- mockSuccess({ code: 200 })
- await api.getWishes({ memberId: 5, status: 'pending' })
- expect(lastRequest().data.memberId).toBe(5)
- })
- test('setWishPrice sends POST with pointsRequired', async () => {
- mockSuccess({ code: 200 })
- await api.setWishPrice(1, 200)
- expect(lastRequest().data.pointsRequired).toBe(200)
- })
- test('approveWishExchange sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.approveWishExchange(1, true)
- expect(lastRequest().data.approved).toBe(true)
- })
- test('createWish sends POST with data', async () => {
- mockSuccess({ code: 200 })
- await api.createWish({ title: '新书包', memberId: 5 })
- expect(lastRequest().data.title).toBe('新书包')
- })
- })
- // --------------- identity parameter hardening ---------------
- // 前端不再向后端发送可伪造的 userId / familyId / childId(仅 memberId),
- // 身份一律由后端从 JWT 推导。以下断言锁定这一不变量。
- describe('identity parameter hardening', () => {
- beforeEach(() => {
- global.uni._storage.token = 'test-token'
- })
- test('request() does NOT send X-User-Id header', async () => {
- mockSuccess({ code: 200 })
- await api.getPendingWishes()
- const opts = lastRequest()
- expect(opts.header['X-User-Id']).toBeUndefined()
- })
- test('getMyAssessmentResults sends empty body, no userId', async () => {
- mockSuccess({ code: 200 })
- await api.getMyAssessmentResults()
- const opts = lastRequest()
- expect(opts.data).toEqual({})
- expect(opts.data.userId).toBeUndefined()
- })
- test('getChildAssessmentResults sends empty body, no userId', async () => {
- mockSuccess({ code: 200 })
- await api.getChildAssessmentResults()
- const opts = lastRequest()
- expect(opts.data).toEqual({})
- expect(opts.data.userId).toBeUndefined()
- })
- test('getTodayTasksByCategory sends only memberId and category', async () => {
- mockSuccess({ code: 200 })
- await api.getTodayTasksByCategory(7, 'wisdom')
- const opts = lastRequest()
- expect(opts.data.memberId).toBe(7)
- expect(opts.data.category).toBe('wisdom')
- expect(opts.data.childId).toBeUndefined()
- expect(opts.data.userId).toBeUndefined()
- })
- })
- // --------------- guide / packages module ---------------
- describe('guide & packages API', () => {
- test('getGuidePackages sends POST to my list', async () => {
- mockSuccess({ code: 200 })
- await api.getGuidePackages(1)
- expect(lastRequest().url).toMatch(/\/api\/guide\/packages\/my$/)
- expect(lastRequest().data.guideId).toBe(1)
- })
- test('registerGuide sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.registerGuide({ name: '张老师', level: 'senior' })
- expect(lastRequest().url).toMatch(/\/api\/guide\/register$/)
- })
- test('generateBindInvite sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.generateBindInvite()
- expect(lastRequest().url).toMatch(/\/api\/guide\/bind\/invite$/)
- })
- test('getBoundFamilies sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getBoundFamilies()
- expect(lastRequest().url).toMatch(/\/api\/guide\/families$/)
- })
- test('getTeamMembers sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getTeamMembers()
- expect(lastRequest().url).toMatch(/\/api\/guide\/team\/members$/)
- })
- test('getGuideOrders sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getGuideOrders()
- expect(lastRequest().url).toMatch(/\/api\/guide\/orders\/list$/)
- })
- test('getGuideMessages sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getGuideMessages()
- expect(lastRequest().url).toMatch(/\/api\/guide\/messages\/list$/)
- })
- })
- // --------------- payment module ---------------
- describe('payment API', () => {
- test('createWechatPayOrder sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.createWechatPayOrder('NO001', '测试订单', 100)
- expect(lastRequest().data.orderNo).toBe('NO001')
- expect(lastRequest().data.amount).toBe(100)
- })
- })
- // --------------- assessment module ---------------
- describe('assessment API', () => {
- test('createAssessmentAppointment sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.createAssessmentAppointment({ memberId: 5, date: '2026-06-20' })
- expect(lastRequest().url).toMatch(/\/api\/dan-assessment\/appointment\/create$/)
- })
- test('payAssessmentOrder sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.payAssessmentOrder('ORDER001', 'wechat')
- expect(lastRequest().data.orderNo).toBe('ORDER001')
- })
- test('recordAssessmentResult sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.recordAssessmentResult({ orderId: 1, score: 85 })
- expect(lastRequest().url).toMatch(/\/api\/dan-assessment\/result\/record$/)
- })
- })
- // --------------- mini-games module ---------------
- describe('mini-games API', () => {
- test('getMiniGameList sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getMiniGameList()
- expect(lastRequest().url).toMatch(/\/api\/mini-game\/list$/)
- })
- test('getMiniGameByCode sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getMiniGameByCode('sudoku')
- expect(lastRequest().url).toMatch(/\/api\/mini-game\/sudoku$/)
- })
- test('completeMiniGame sends POST with game data', async () => {
- mockSuccess({ code: 200 })
- await api.completeMiniGame(5, 'sudoku', 120, 85)
- expect(lastRequest().data.memberId).toBe(5)
- expect(lastRequest().data.gameCode).toBe('sudoku')
- expect(lastRequest().data.completionTime).toBe(120)
- expect(lastRequest().data.score).toBe(85)
- })
- test('getGameHistory sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getGameHistory({ memberId: 5 })
- expect(lastRequest().url).toMatch(/\/api\/game\/history$/)
- })
- test('getGameLeaderboard sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getGameLeaderboard({ gameCode: 'sudoku' })
- expect(lastRequest().url).toMatch(/\/api\/game\/leaderboard$/)
- })
- })
- // --------------- growth module ---------------
- describe('growth records API', () => {
- test('createGrowthRecord sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.createGrowthRecord({ memberId: 5, content: '长高了2cm' })
- expect(lastRequest().url).toMatch(/\/api\/growth\/record\/create$/)
- })
- test('getGrowthRecordList sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getGrowthRecordList()
- expect(lastRequest().url).toMatch(/\/api\/growth\/record\/list$/)
- })
- test('createGrowthRecord with alsoPurchaseAssessment uses merge endpoint', async () => {
- mockSuccess({ code: 200 })
- await api.createGrowthRecord({ memberId: 5, alsoPurchaseAssessment: true })
- expect(lastRequest().url).toMatch(/\/api\/growth\/record\/create-with-order$/)
- })
- })
- // --------------- energy module ---------------
- describe('energy API', () => {
- test('getEnergyOverview sends POST with memberId', async () => {
- mockSuccess({ code: 200 })
- await api.getEnergyOverview(5)
- expect(lastRequest().data.memberId).toBe(5)
- })
- test('getEnergyLogs sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getEnergyLogs(5, 'body', 1, 20)
- expect(lastRequest().data.dimensionCode).toBe('body')
- })
- test('getFamilyEnergySandbox sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getFamilyEnergySandbox()
- expect(lastRequest().url).toMatch(/\/api\/energy\/sandbox$/)
- })
- })
- // --------------- badges module ---------------
- describe('badges API', () => {
- test('getActiveBadges sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getActiveBadges()
- expect(lastRequest().url).toMatch(/\/api\/badges\/list$/)
- })
- test('getChildBadges sends POST with memberId', async () => {
- mockSuccess({ code: 200 })
- await api.getChildBadges(5)
- expect(lastRequest().data.memberId).toBe(5)
- })
- test('toggleBadgeFavorite sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.toggleBadgeFavorite(5, 3)
- expect(lastRequest().data.memberId).toBe(5)
- expect(lastRequest().data.badgeId).toBe(3)
- })
- })
- // --------------- articles module ---------------
- describe('articles API', () => {
- test('getArticleCategories sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getArticleCategories()
- expect(lastRequest().url).toMatch(/\/api\/articles\/categories$/)
- })
- test('getArticleList sends POST with data', async () => {
- mockSuccess({ code: 200 })
- await api.getArticleList({ categoryId: 1, page: 1 })
- expect(lastRequest().url).toMatch(/\/api\/articles\/list$/)
- })
- test('getArticleDetail sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getArticleDetail({ id: 42 })
- expect(lastRequest().url).toMatch(/\/api\/articles\/detail$/)
- })
- test('getDailyTip sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getDailyTip()
- expect(lastRequest().url).toMatch(/\/api\/articles\/daily-tip$/)
- })
- })
- // --------------- contact module ---------------
- describe('contact API', () => {
- test('getContactList sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getContactList({ memberId: 5 })
- expect(lastRequest().url).toMatch(/\/api\/contact\/list$/)
- })
- test('createContact sends POST with data', async () => {
- mockSuccess({ code: 200 })
- await api.createContact({ name: '爷爷', relation: 'grandfather' })
- expect(lastRequest().url).toMatch(/\/api\/contact\/create$/)
- })
- test('deleteContact sends POST with id', async () => {
- mockSuccess({ code: 200 })
- await api.deleteContact(3)
- expect(lastRequest().url).toMatch(/\/api\/contact\/delete$/)
- expect(lastRequest().data.id).toBe(3)
- })
- test('importPhoneContact sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.importPhoneContact({ contacts: [{ name: '张三', phone: '13800138000' }] })
- expect(lastRequest().url).toMatch(/\/api\/contact\/import-phone$/)
- })
- })
- // --------------- vendor module ---------------
- describe('vendor API', () => {
- test('vendorApply sends POST with data', async () => {
- mockSuccess({ code: 200 })
- await api.vendorApply({ companyName: '某某公司', type: 'planner' })
- expect(lastRequest().url).toMatch(/\/api\/vendor\/apply$/)
- })
- test('vendorStatus sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.vendorStatus()
- expect(lastRequest().url).toMatch(/\/api\/vendor\/status$/)
- })
- test('vendorInfo sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.vendorInfo()
- expect(lastRequest().url).toMatch(/\/api\/vendor\/info$/)
- })
- })
- // --------------- product module ---------------
- describe('product API', () => {
- test('productList sends POST', () => {
- // productList uses new Promise without success/fail callbacks,
- // so we check the request synchronously.
- api.productList({ page: 1, size: 10 })
- const opts = lastRequest()
- expect(opts.method).toBe('POST')
- expect(opts.url).toMatch(/\/api\/product\/list$/)
- })
- test('productDetail sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.productDetail({ id: 1 })
- expect(lastRequest().url).toMatch(/\/api\/product\/detail$/)
- })
- test('productCreate sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.productCreate({ name: '测试商品', price: 100 })
- expect(lastRequest().url).toMatch(/\/api\/product\/create$/)
- })
- test('productOrderCreate sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.productOrderCreate({ productId: 1, quantity: 2 })
- expect(lastRequest().url).toMatch(/\/api\/product\/order\/create$/)
- })
- })
- // --------------- commission / invite ---------------
- describe('commission & invite API', () => {
- test('getReferralCode sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getReferralCode()
- expect(lastRequest().url).toMatch(/\/api\/invite\/code$/)
- })
- test('bindReferral sends POST with code', async () => {
- mockSuccess({ code: 200 })
- await api.bindReferral('ABC123')
- expect(lastRequest().data.referralCode).toBe('ABC123')
- })
- test('getCommissionSummary sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getCommissionSummary()
- expect(lastRequest().url).toMatch(/\/api\/commission\/summary$/)
- })
- test('applyWithdrawal sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.applyWithdrawal(500, { bank: 'ICBC', account: '6222****' })
- expect(lastRequest().data.amount).toBe(500)
- })
- })
- // --------------- stats module ---------------
- describe('stats API', () => {
- test('getChildCompletionStats sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getChildCompletionStats({ memberId: 5 })
- expect(lastRequest().url).toMatch(/\/api\/stats\/child-completion$/)
- })
- test('getChildOverview sends POST with memberId', async () => {
- mockSuccess({ code: 200 })
- await api.getChildOverview(5)
- expect(lastRequest().data.memberId).toBe(5)
- })
- })
- // --------------- AI chat module ---------------
- describe('AI chat API', () => {
- test('aiSendMessage sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.aiSendMessage({ conversationId: 1, content: '你好' })
- expect(lastRequest().url).toMatch(/\/api\/ai\/chat\/send$/)
- })
- test('aiGetConversations sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.aiGetConversations()
- expect(lastRequest().url).toMatch(/\/api\/ai\/chat\/conversations$/)
- })
- })
- // --------------- health / wealth module ---------------
- // --------------- health report module (new) ---------------
- describe('health report API', () => {
- test('createHealthReport sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.createHealthReport({ memberId: 5, reportData: { height: 120, weight: 22 } })
- expect(lastRequest().url).toMatch(/\/api\/health\/report\/create$/)
- expect(lastRequest().data.memberId).toBe(5)
- })
- test('getReportList sends POST with memberId', async () => {
- mockSuccess({ code: 200 })
- await api.getReportList(5)
- expect(lastRequest().url).toMatch(/\/api\/health\/report\/list$/)
- expect(lastRequest().data.memberId).toBe(5)
- })
- test('getReportDetail sends POST with reportId', async () => {
- mockSuccess({ code: 200 })
- await api.getReportDetail(42)
- expect(lastRequest().url).toMatch(/\/api\/health\/report\/detail$/)
- expect(lastRequest().data.reportId).toBe(42)
- })
- test('getLatestHealthReport sends POST with memberId', async () => {
- mockSuccess({ code: 200 })
- await api.getLatestHealthReport(5)
- expect(lastRequest().url).toMatch(/\/api\/health\/report\/latest$/)
- expect(lastRequest().data.memberId).toBe(5)
- })
- test('getHealthIndicatorList sends POST with memberId', async () => {
- mockSuccess({ code: 200 })
- await api.getHealthIndicatorList(5)
- expect(lastRequest().url).toMatch(/\/api\/health\/indicator\/list$/)
- expect(lastRequest().data.memberId).toBe(5)
- })
- test('createReportSurvey sends POST with reportId and memberId', async () => {
- mockSuccess({ code: 200 })
- await api.createReportSurvey(10, 5)
- expect(lastRequest().url).toMatch(/\/api\/health\/survey\/create$/)
- expect(lastRequest().data.reportId).toBe(10)
- expect(lastRequest().data.memberId).toBe(5)
- })
- test('submitReportSurvey sends POST with surveyId and data', async () => {
- mockSuccess({ code: 200 })
- await api.submitReportSurvey(1, { q1: 'yes', q2: 'no' })
- expect(lastRequest().url).toMatch(/\/api\/health\/survey\/submit$/)
- expect(lastRequest().data.surveyId).toBe(1)
- expect(lastRequest().data.surveyData.q1).toBe('yes')
- })
- test('getSurveyStatus sends POST with reportId', async () => {
- mockSuccess({ code: 200 })
- await api.getSurveyStatus({ reportId: 10 })
- expect(lastRequest().url).toMatch(/\/api\/survey\/status$/)
- expect(lastRequest().data.reportId).toBe(10)
- })
- })
- describe('health & wealth API', () => {
- test('healthCheckinList sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.healthCheckinList({ memberId: 5 })
- expect(lastRequest().url).toMatch(/\/api\/health\/checkin\/list$/)
- })
- test('getCheckinList sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getCheckinList({ memberId: 5 })
- expect(lastRequest().url).toMatch(/\/api\/wealth\/checkin\/list$/)
- })
- test('getInsuranceList sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.getInsuranceList({ memberId: 5 })
- expect(lastRequest().url).toMatch(/\/api\/wealth\/insurance\/list$/)
- })
- })
- // --------------- invite card module ---------------
- describe('invite card API', () => {
- test('generateInviteCard sends POST', async () => {
- mockSuccess({ code: 200 })
- await api.generateInviteCard('guide', 1)
- expect(lastRequest().data.type).toBe('guide')
- })
- test('verifyInviteCard sends POST with code', async () => {
- mockSuccess({ code: 200 })
- await api.verifyInviteCard('CARD123')
- expect(lastRequest().data.code).toBe('CARD123')
- })
- })
|