growthHistory.view.test.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. /**
  2. * 契约级单测(TDD-RED)——能力键 growth.history.view(SC-P-95 / 变更B)
  3. *
  4. * 溯源:
  5. * requirement: tests/user-scenarios/应用场景总览.md SC-P-95
  6. * docs/需求分析/2026-11-06-成就成长打卡需求变更.md §变更B(成长记录→成长历史记录页)
  7. * design: cfc-frontend/pages/growth-main/index.vue「今日成长」网格
  8. * cfc-frontend/utils/api.js getGrowthRecordList(~L1409,POST /api/growth/record/list)
  9. * healthCheckinList(~L2253,POST /api/health/checkin/list)
  10. *
  11. * 说明(既有 Jest 体系约束):
  12. * cfc-frontend 的 jest.config.js 仅 transform `.js`(babel-jest),moduleFileExtensions 不含 `vue`,
  13. * 且未安装 vue-jest/jsdom 组件环境 —— 既有约定为「抽取被测逻辑断言」而非挂载 .vue
  14. * (见 __tests__/components/FamilyRelationGraph.test.js,导入 shallowMount 但实际只测抽取函数;
  15. * 本文件沿用 reference 风格 __tests__/family-join/join-form.required-info.test.js —— 直接加载真实
  16. * SFC 的 <script>/<template> 源码做结构/行为契约断言;纯 fs 读取,无渲染引擎)。
  17. * - <script>:把 import 语句替换为注入桩后求值,得到真实组件的 data()/methods,做行为级断言;
  18. * - <template>:读取模板文本,做结构契约断言(今日成长网格容器、历史按日期分组渲染)。
  19. *
  20. * 红/绿判定:
  21. * - 页面存在、今日成长网格、两个 API 封装(URL/POST 方法)——现状已合入 origin/cfclub → 绿(无回归锚点);
  22. * - 「成长历史记录按日期分组渲染」(变更B 验收口径:看到所有打卡记录,按日期倒序/分组)——
  23. * 现状 growth-main/index.vue 仅渲染「今日成长」progressItems 网格,无任何按日期分组的
  24. * 历史记录结构 → 红(契约缺口,即 RED 核心)。GREEN 实现方需在 growth-main 页面补足
  25. * 下列命名契约(或对齐本文件断言):模板 v-for 数据源为 dateGroups/groupedRecords/
  26. * groupedCheckins/historyGroups/checkinGroups/recordGroups/dayGroups 之一,或 methods
  27. * (/computed)提供 groupByDate/groupRecordsByDate/groupCheckinsByDate/groupHistoryByDate。
  28. *
  29. * 本文件不修改 pages/、utils/ 任何业务代码。
  30. */
  31. import fs from 'fs'
  32. import path from 'path'
  33. import { getGrowthRecordList as apiGetGrowthRecordList, healthCheckinList as apiHealthCheckinList, clearApiDedup } from '@/utils/api'
  34. const GROWTH_MAIN_PATH = path.join(__dirname, '../../../pages/growth-main/index.vue')
  35. // ---------------------------------------------------------------------------
  36. // 工具:加载真实 growth-main/index.vue 的 <script> 逻辑(行为级)与 <template> 结构(结构级)
  37. // ---------------------------------------------------------------------------
  38. /** 把 ES import 语句替换为从 globalThis.__growthHistoryStubs 取桩的声明(不解析模块,避免污染业务实现) */
  39. function stubImports(script, stubMap) {
  40. return script.replace(/import\s+([^;]+?)\s+from\s+['"]([^'"]+)['"];?/g, function (m, clause, id) {
  41. var names = []
  42. var c = clause.trim()
  43. var braceIdx = c.indexOf('{')
  44. if (braceIdx >= 0) {
  45. var def = c.slice(0, braceIdx).replace(/,\s*$/, '').trim()
  46. if (def) names.push(def)
  47. var named = c.slice(braceIdx + 1, c.lastIndexOf('}'))
  48. named.split(',').forEach(function (part) {
  49. var p = part.trim()
  50. if (!p) return
  51. var parts = p.split(/\s+as\s+/)
  52. var local = parts.length > 1 ? parts[1].trim() : parts[0].trim()
  53. if (local) names.push(local)
  54. })
  55. } else if (c.indexOf('*') === 0) {
  56. var nsMatch = c.match(/\*\s+as\s+(\w+)/)
  57. if (nsMatch) names.push(nsMatch[1])
  58. } else {
  59. names.push(c)
  60. }
  61. return names.map(function (n) {
  62. return 'var ' + n + ' = (globalThis.__growthHistoryStubs[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
  63. }).join('\n')
  64. })
  65. }
  66. /** 加载真实 SFC:返回 { component, template }(component = 真实 <script> 的 export default 对象) */
  67. function loadGrowthMain() {
  68. var src = fs.readFileSync(GROWTH_MAIN_PATH, 'utf8')
  69. var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
  70. var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
  71. if (!scriptMatch) throw new Error('无法在 growth-main/index.vue 中定位 <script> 块')
  72. var script = stubImports(scriptMatch[1], globalThis.__growthHistoryStubs || {})
  73. script = script.replace(/export default\s*\{/, 'module.exports = {')
  74. var mod = { exports: {} }
  75. // eslint-disable-next-line no-new-func
  76. var fn = new Function('module', 'exports', script)
  77. fn(mod, mod.exports)
  78. return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '' }
  79. }
  80. /** 依据真实组件的 data()/methods 构造可驱动上下文(模拟 Vue 把 data 与 methods 合并到实例) */
  81. function instantiate(component) {
  82. var vm = {}
  83. var data = typeof component.data === 'function' ? component.data.call(vm) : (component.data || {})
  84. Object.keys(data).forEach(function (k) { vm[k] = data[k] })
  85. var methods = component.methods || {}
  86. Object.keys(methods).forEach(function (k) { vm[k] = methods[k] })
  87. // 顶层生命周期钩子(onShow/onLoad 等)不在 methods 内,直接取自组件根对象
  88. Object.keys(component).forEach(function (k) {
  89. if (typeof component[k] === 'function' && vm[k] === undefined) vm[k] = component[k]
  90. })
  91. return vm
  92. }
  93. // ---------------------------------------------------------------------------
  94. // 测试夹具
  95. // ---------------------------------------------------------------------------
  96. var stubs
  97. beforeEach(function () {
  98. global.uni._storage = {}
  99. global.uni.showToast.mockReset()
  100. global.uni.reLaunch.mockReset()
  101. global.uni.request.mockReset()
  102. // growth-main 的 <script> 会声明 9 个 API 依赖:只 stub 组件运行时真正调用的,
  103. // 其余以空实现兜底,避免 eval 阶段缺名(var 未定义即可,方法体才使用)
  104. stubs = {
  105. healthCheckinList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
  106. getHealthMealList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
  107. getGrowthRecommendations: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: { articles: [] } }) }),
  108. getExerciseRecords: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
  109. getSleepRecords: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
  110. getEmotionCheckinList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
  111. getCheckinList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
  112. getTodayTasks: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
  113. reportAppEnter: jest.fn(),
  114. getGrowthRecordList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
  115. parseDate: jest.fn(function (v) { return v ? new Date(String(v).replace(/-/g, '/')) : null }),
  116. recordDateOf: jest.fn(function () { return '' }),
  117. fontScaleMixin: { data: function () { return { fontScale: 1 } }, onShow: function () {} },
  118. shareMixin: {}
  119. }
  120. globalThis.__growthHistoryStubs = {
  121. // 注意:growth-main/index.vue 的 import 使用相对路径(../../utils/api.js 等),桩键须与真实 import id 一致
  122. '../../utils/api.js': {
  123. healthCheckinList: stubs.healthCheckinList,
  124. getHealthMealList: stubs.getHealthMealList,
  125. getGrowthRecommendations: stubs.getGrowthRecommendations,
  126. getExerciseRecords: stubs.getExerciseRecords,
  127. getSleepRecords: stubs.getSleepRecords,
  128. getEmotionCheckinList: stubs.getEmotionCheckinList,
  129. getCheckinList: stubs.getCheckinList,
  130. getTodayTasks: stubs.getTodayTasks,
  131. reportAppEnter: stubs.reportAppEnter
  132. },
  133. '../../utils/format.js': { parseDate: stubs.parseDate, recordDateOf: stubs.recordDateOf },
  134. '@/mixins/font-scale.js': { fontScaleMixin: stubs.fontScaleMixin },
  135. '../../components/share-mixin.js': { shareMixin: stubs.shareMixin },
  136. '../../components/LoginGuideCard.vue': {},
  137. '../../components/DimensionActivities.vue': {},
  138. '../../components/DimensionProducts.vue': {},
  139. '../../components/ArticleFeed.vue': {}
  140. }
  141. jest.useFakeTimers()
  142. })
  143. afterEach(function () {
  144. jest.useRealTimers()
  145. delete globalThis.__growthHistoryStubs
  146. })
  147. // ---------------------------------------------------------------------------
  148. // AC_CONTRACT_1 | 页面存在 + 今日成长网格结构契约(现状锚点,预期绿)
  149. // ---------------------------------------------------------------------------
  150. describe('AC_CONTRACT_1 页面存在与今日成长网格结构(现状锚点)', function () {
  151. var template
  152. beforeAll(function () {
  153. // beforeAll 先于 beforeEach 执行:仅做模板结构断言,无需桩函数,置空即可(loadGrowthMain 对桩做可选访问)
  154. globalThis.__growthHistoryStubs = {}
  155. template = loadGrowthMain().template
  156. })
  157. it('被测页面 growth-main/index.vue 存在且可解析(含 template/script 块)', function () {
  158. expect(fs.existsSync(GROWTH_MAIN_PATH)).toBe(true)
  159. expect(template.length).toBeGreaterThan(0)
  160. })
  161. it('今日成长区域容器存在(progress-card / progress-title)', function () {
  162. expect(template).toMatch(/progress-card/)
  163. expect(template).toMatch(/今日成长/)
  164. })
  165. it('今日成长网格容器存在(progress-grid),按 progressItems 渲染', function () {
  166. expect(template).toMatch(/class="progress-grid"/)
  167. expect(template).toMatch(/progressItems\.length > 0/)
  168. })
  169. it('网格渲染项存在:progress-tile v-for 循环 + :key + 点击处理器', function () {
  170. expect(template).toMatch(/class="progress-tile"[^>]*v-for="\(item, idx\) in progressItems"/)
  171. expect(template).toMatch(/:key="getProgressKey\(item\)"/)
  172. expect(template).toMatch(/handleProgressClick\(idx\)/)
  173. })
  174. it('今日成长六项打卡(饮食/运动/睡眠/心情/记账 + 更多任务)为结构的一部分(无回归锚点)', function () {
  175. expect(template).toMatch(/饮食/)
  176. expect(template).toMatch(/运动/)
  177. expect(template).toMatch(/睡眠/)
  178. expect(template).toMatch(/心情/)
  179. expect(template).toMatch(/记账/)
  180. expect(template).toMatch(/更多任务/)
  181. })
  182. })
  183. // ---------------------------------------------------------------------------
  184. // AC_CONTRACT_2 | 成长历史按日期分组渲染(变更B 验收口径:看到所有打卡记录、按日期分组)
  185. // 现状 growth-main/index.vue 仅渲染「今日成长」,无按日期分组结构 → 预期红(RED 核心)
  186. // ---------------------------------------------------------------------------
  187. describe('AC_CONTRACT_2 成长历史记录按日期分组渲染(变更B → 预期红)', function () {
  188. var src
  189. beforeAll(function () {
  190. // 直接扫描原始 SFC 全文(template + script 原始文本):methods/computed 不能被序列化丢弃,
  191. // 日期分组装配逻辑须在原始 <script> 源码中可见
  192. src = fs.readFileSync(GROWTH_MAIN_PATH, 'utf8')
  193. })
  194. it('RED#1 模板存在「按日期分组」的记录循环渲染(如 v-for 于 dateGroups/groupedRecords/historyGroups 等)', function () {
  195. // GREEN 实现契约:历史记录须以「日期分组集合」为 v-for 数据源渲染(dateGroups | groupedRecords |
  196. // groupedCheckins | historyGroups | checkinGroups | recordGroups | dayGroups | growthHistoryGroups)
  197. expect(src).toMatch(/v-for\s*=\s*["'][^"']*(?:dateGroups|dateGroupList|groupedRecords|groupedCheckins|historyGroups|historyDays|checkinGroups|recordGroups|dayGroups|growthHistoryGroups)[^"']*["']/i)
  198. })
  199. it('RED#2 组件提供按日期分组的装配逻辑(methods/computed 存在 groupByDate 系方法)', function () {
  200. // GREEN 实现契约:组件需提供把打卡/档案记录流按日期分组的装配入口
  201. // (groupByDate | groupRecordsByDate | groupCheckinsByDate | groupHistoryByDate | groupedByDate)
  202. expect(src).toMatch(/(?:groupByDate|groupRecordsByDate|groupCheckinsByDate|groupHistoryByDate|groupedByDate)\s*(?:\(|:)/i)
  203. })
  204. })
  205. // ---------------------------------------------------------------------------
  206. // AC_CONTRACT_3 | 行为级:真实组件 data()/methods —— 今日成长数据装配(现状锚点,预期绿)
  207. // ---------------------------------------------------------------------------
  208. describe('AC_CONTRACT_3 真实组件行为:今日成长数据装配(现状锚点)', function () {
  209. var vm
  210. beforeEach(function () {
  211. var component = loadGrowthMain().component
  212. vm = instantiate(component)
  213. })
  214. it('data 提供 progressItems 数组(今日成长网格数据源)', function () {
  215. expect(Array.isArray(vm.progressItems)).toBe(true)
  216. expect(vm.todayDate).toBe('')
  217. })
  218. it('onShow 设置 todayDate 为今日 yyyy-MM-dd 并调用 loadAllData(已登录态)', async function () {
  219. global.uni.setStorageSync('token', 'T-1')
  220. global.uni.setStorageSync('currentChildId', '88')
  221. await vm.onShow()
  222. expect(vm.todayDate).toMatch(/^\d{4}-\d{2}-\d{2}$/)
  223. var now = new Date()
  224. var pad = function (n) { return n < 10 ? '0' + n : '' + n }
  225. expect(vm.todayDate).toBe(now.getFullYear() + '-' + pad(now.getMonth() + 1) + '-' + pad(now.getDate()))
  226. expect(vm.isLoggedIn).toBe(true)
  227. expect(stubs.reportAppEnter).toHaveBeenCalledWith('growth')
  228. })
  229. it('loadProgressItems 装配六项打卡(diet/exercise/sleep/emotion/checkin + 更多任务入口)', async function () {
  230. await vm.loadProgressItems()
  231. expect(stubs.getTodayTasks).toHaveBeenCalled()
  232. expect(Array.isArray(vm.progressItems)).toBe(true)
  233. var keys = vm.progressItems.map(function (it) { return it.key })
  234. expect(keys).toEqual(expect.arrayContaining(['diet', 'exercise', 'sleep', 'emotion', 'checkin']))
  235. expect(vm.progressItems.length).toBeGreaterThanOrEqual(5)
  236. })
  237. it('loadMilestones 通过 healthCheckinList 拉取连续打卡天数(限 30 天封顶的既有锚点)', async function () {
  238. stubs.healthCheckinList.mockResolvedValueOnce({ code: 200, message: 'ok', data: [1, 2, 3] })
  239. await vm.loadMilestones()
  240. expect(stubs.healthCheckinList).toHaveBeenCalled()
  241. expect(vm.streakDays).toBe(3)
  242. expect(vm.completeness).toBe(30)
  243. })
  244. })
  245. // ---------------------------------------------------------------------------
  246. // AC_CONTRACT_4 | 设计锚点:utils/api.js 封装契约(现状已合入,预期绿)
  247. // getGrowthRecordList → POST /api/growth/record/list
  248. // healthCheckinList → POST /api/health/checkin/list
  249. // ---------------------------------------------------------------------------
  250. describe('AC_CONTRACT_4 设计锚点:api.js 封装 URL/方法契约', function () {
  251. it('getGrowthRecordList 发起 POST /api/growth/record/list', async function () {
  252. var captured = null
  253. global.uni.request.mockImplementation(function (opts) {
  254. captured = opts
  255. process.nextTick(function () { opts.success({ data: { code: 200, message: 'ok', data: [] } }) })
  256. })
  257. clearApiDedup()
  258. await apiGetGrowthRecordList()
  259. expect(captured.url).toContain('/api/growth/record/list')
  260. expect(captured.method).toBe('POST')
  261. })
  262. it('healthCheckinList 发起 POST /api/health/checkin/list 并透传请求体', async function () {
  263. var captured = null
  264. global.uni.request.mockImplementation(function (opts) {
  265. captured = opts
  266. process.nextTick(function () { opts.success({ data: { code: 200, message: 'ok', data: [] } }) })
  267. })
  268. clearApiDedup()
  269. await apiHealthCheckinList({ memberId: 88, page: 1, size: 20 })
  270. expect(captured.url).toContain('/api/health/checkin/list')
  271. expect(captured.method).toBe('POST')
  272. expect(captured.data).toEqual(expect.objectContaining({ memberId: 88, page: 1, size: 20 }))
  273. })
  274. })
  275. // ---------------------------------------------------------------------------
  276. // 权限流:本能力为「家长查看孩子成长/打卡历史」,页面在已登录态按 currentChildId 取数,
  277. // 无额外 role 门禁分支(role 校验在后端 JwtInterceptor 层),显式记录为不适用项。
  278. // ---------------------------------------------------------------------------
  279. describe.skip('权限流:成长历史查看无前端 role 门禁分支,不适用', function () {
  280. it('占位:该能力面向登录家长/教师查看成长记录,详见汇报', function () {})
  281. })