growthHistory.dayGroupView.test.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. /**
  2. * 契约级单测(TDD-RED)——能力键 growth.history.dayGroupView(成长主页「按日期分组」视图)
  3. *
  4. * 溯源:
  5. * requirement: tests/user-scenarios/应用场景总览.md SC-P-95
  6. * docs/需求分析/2026-11-06-成就成长打卡需求变更.md §变更B(成长记录→成长历史记录页,
  7. * 聚合「今日成长」全部打卡记录,按日期倒序、分组/筛选,空态合理)
  8. * docs/tdd/test/blockers.md B-135-1(frontend 16 红 = growth-main 按日期分组未落地)
  9. * design: cfc-frontend/pages/growth-main/index.vue(补按日期分组:dateGroups/groupedRecords/
  10. * groupByDate 结构;实现仅在 feature 分支,不得假定包路径,本测试命名契约对齐同批
  11. * growthHistory.view.test.js 的容错清单——data 字段 v-for 源与 groupByDate 系方法均可选名)
  12. * 同批参考: cfc-frontend/__tests__/pages/growth-main/growthHistory.view.test.js(S-cfc-30,已合入,
  13. * 仅含 2 条结构级 RED 断言)· cfc-frontend/__tests__/family-join/join-form.required-info.test.js(加载真实 SFC 源码)
  14. *
  15. * 说明(既有 Jest 体系约束,同 growthHistory.view.test.js):
  16. * cfc-frontend 的 jest.config.js 仅 transform `.js`,moduleFileExtensions 不含 `vue`,无 vue-jest/jsdom
  17. * 组件环境 —— 既有约定为「抽取被测逻辑断言」:直接加载真实 SFC 的 <script>/<template> 源码——
  18. * - <script>:把 import 语句替换为注入桩后求值,得到真实组件的 data()/methods,做行为级断言;
  19. * - <template>:读取模板文本,做结构契约断言(按日期分组循环、日期标题、空态分支)。
  20. * format.js 的 parseDate/recordDateOf 注入**真实实现**(纯函数),使分组行为契约覆盖后端真实
  21. * 日期形态(recordDate 纯日期 / sleepTime MySQL 空格格式 / startTime ISO / checkinDate 纯日期)。
  22. *
  23. * 红/绿判定:
  24. * - 现状 origin/cfclub 的 growth-main/index.vue 仅有「今日成长」progressItems 网格,data 无
  25. * dateGroups 系字段、methods 无 groupByDate 系方法、模板无按日期分组渲染 → 全部预期**红**(RED 核心)。
  26. * - 使绿改动(GREEN 阶段实现方,仅改 src/main 下本页面,不动本测试):
  27. * ① data 增补日期分组状态字段(dateGroups/dateGroupList/groupedRecords/groupedCheckins/
  28. * historyGroups/historyDays/checkinGroups/recordGroups/dayGroups/growthHistoryGroups 之一,默认 []);
  29. * ② methods 提供把打卡/档案记录流按业务日期(recordDate>startTime>sleepTime>checkinDate>createdAt)
  30. * 分组的装配入口(groupByDate/groupRecordsByDate/groupCheckinsByDate/groupHistoryByDate/groupedByDate
  31. * 之一):同日合并、分组键 yyyy-MM-dd、多日倒序(新在前)、无有效日期平稳跳过;
  32. * ③ 模板以分组集合为 v-for 渲染,分组标题显示日期,集合为空时有空态分支(文案/条件均可)。
  33. *
  34. * 本文件不修改 pages/、utils/ 任何业务代码。
  35. */
  36. import fs from 'fs'
  37. import path from 'path'
  38. // format.js 为纯函数工具,注入真实实现保证分组行为契约覆盖后端真实日期形态(与桩隔离无冲突)
  39. import { parseDate as realParseDate, recordDateOf as realRecordDateOf } from '@/utils/format'
  40. const GROWTH_MAIN_PATH = path.join(__dirname, '../../../pages/growth-main/index.vue')
  41. // 容错命名清单(对齐已合入 growthHistory.view.test.js 的契约,或按之对齐即可)
  42. const DATA_FIELD_NAMES = ['dateGroups', 'dateGroupList', 'groupedRecords', 'groupedCheckins', 'historyGroups', 'historyDays', 'checkinGroups', 'recordGroups', 'dayGroups', 'growthHistoryGroups']
  43. const METHOD_NAMES = ['groupByDate', 'groupRecordsByDate', 'groupCheckinsByDate', 'groupHistoryByDate', 'groupedByDate']
  44. // ---------------------------------------------------------------------------
  45. // 工具:加载真实 growth-main/index.vue 的 <script> 逻辑(行为级)与 <template> 结构(结构级)
  46. // ---------------------------------------------------------------------------
  47. /** 把 ES import 语句替换为从 globalThis.__dayGroupViewStubs 取桩的声明(不解析模块,避免污染业务实现) */
  48. function stubImports(script, stubMap) {
  49. return script.replace(/import\s+([^;]+?)\s+from\s+['"]([^'"]+)['"];?/g, function (m, clause, id) {
  50. var names = []
  51. var c = clause.trim()
  52. var braceIdx = c.indexOf('{')
  53. if (braceIdx >= 0) {
  54. var def = c.slice(0, braceIdx).replace(/,\s*$/, '').trim()
  55. if (def) names.push(def)
  56. var named = c.slice(braceIdx + 1, c.lastIndexOf('}'))
  57. named.split(',').forEach(function (part) {
  58. var p = part.trim()
  59. if (!p) return
  60. var parts = p.split(/\s+as\s+/)
  61. var local = parts.length > 1 ? parts[1].trim() : parts[0].trim()
  62. if (local) names.push(local)
  63. })
  64. } else if (c.indexOf('*') === 0) {
  65. var nsMatch = c.match(/\*\s+as\s+(\w+)/)
  66. if (nsMatch) names.push(nsMatch[1])
  67. } else {
  68. names.push(c)
  69. }
  70. return names.map(function (n) {
  71. return 'var ' + n + ' = (globalThis.__dayGroupViewStubs[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
  72. }).join('\n')
  73. })
  74. }
  75. /** 加载真实 SFC:返回 { component, template }(component = 真实 <script> 的 export default 对象) */
  76. function loadGrowthMain() {
  77. var src = fs.readFileSync(GROWTH_MAIN_PATH, 'utf8')
  78. var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
  79. var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
  80. if (!scriptMatch) throw new Error('无法在 growth-main/index.vue 中定位 <script> 块')
  81. var script = stubImports(scriptMatch[1], globalThis.__dayGroupViewStubs || {})
  82. script = script.replace(/export default\s*\{/, 'module.exports = {')
  83. var mod = { exports: {} }
  84. // eslint-disable-next-line no-new-func
  85. var fn = new Function('module', 'exports', script)
  86. fn(mod, mod.exports)
  87. return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '' }
  88. }
  89. /** 依据真实组件的 data()/methods 构造可驱动上下文(模拟 Vue 把 data 与 methods 合并到实例) */
  90. function instantiate(component) {
  91. var vm = {}
  92. var data = typeof component.data === 'function' ? component.data.call(vm) : (component.data || {})
  93. Object.keys(data).forEach(function (k) { vm[k] = data[k] })
  94. var methods = component.methods || {}
  95. Object.keys(methods).forEach(function (k) { vm[k] = methods[k] })
  96. return vm
  97. }
  98. /** 在真实组件中查找 groupByDate 系装配方法的第一个命中名(无则 null) */
  99. function findGroupMethodName(component) {
  100. var methods = component.methods || {}
  101. for (var i = 0; i < METHOD_NAMES.length; i++) {
  102. if (typeof methods[METHOD_NAMES[i]] === 'function') return METHOD_NAMES[i]
  103. }
  104. return null
  105. }
  106. /** 以真实组件 methods 装配入口驱动分组(方法缺失返回 undefined,由断言暴露契约缺口) */
  107. function invokeGrouping(component, records) {
  108. var name = findGroupMethodName(component)
  109. if (!name) return undefined
  110. var vm = instantiate(component)
  111. return vm[name](records)
  112. }
  113. /** 归一化分组形状(兼容 date/day/groupDate/dayKey/dateStr × records/list/items/checkins/data 命名) */
  114. function normalizeGroup(g) {
  115. var date = g && (g.date || g.day || g.groupDate || g.dayKey || g.dateStr || '')
  116. var list = g && (g.records || g.list || g.items || g.checkins || g.data || [])
  117. return { date: String(date), list: list }
  118. }
  119. // ---------------------------------------------------------------------------
  120. // 测试夹具
  121. // ---------------------------------------------------------------------------
  122. /** 混合类型打卡记录流(业务日期字段仿后端真实形态:饮食 recordDate / 睡眠 sleepTime / 运动 startTime / 心情·记账 checkinDate) */
  123. function sampleRecords() {
  124. return [
  125. { type: 'diet', recordDate: '2026-11-08', name: '早餐' },
  126. { type: 'sleep', sleepTime: '2026-11-08 23:00', note: '正常' },
  127. { type: 'exercise', startTime: '2026-11-07T08:30:00', minutes: 30 },
  128. { type: 'emotion', checkinDate: '2026-11-07', mood: '开心' },
  129. { type: 'checkin', checkinDate: '2026-11-06', amount: 50 },
  130. { type: 'growth', recordDate: '2026-11-06', content: '阅读 30 分钟' },
  131. { type: 'diet-backfill', recordDate: '2026-11-09', name: '午餐补录' }
  132. ]
  133. }
  134. var stubs
  135. beforeEach(function () {
  136. global.uni._storage = {}
  137. global.uni.showToast.mockReset()
  138. global.uni.reLaunch.mockReset()
  139. global.uni.request.mockReset()
  140. // growth-main 的 <script> 会声明 9 个 API 依赖:只 stub 组件运行时真正调用的,其余以空实现兜底
  141. stubs = {
  142. healthCheckinList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
  143. getHealthMealList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
  144. getGrowthRecommendations: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: { articles: [] } }) }),
  145. getExerciseRecords: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
  146. getSleepRecords: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
  147. getEmotionCheckinList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
  148. getCheckinList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
  149. getTodayTasks: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
  150. reportAppEnter: jest.fn(),
  151. getGrowthRecordList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) })
  152. }
  153. globalThis.__dayGroupViewStubs = {
  154. '../../utils/api.js': {
  155. healthCheckinList: stubs.healthCheckinList,
  156. getHealthMealList: stubs.getHealthMealList,
  157. getGrowthRecommendations: stubs.getGrowthRecommendations,
  158. getExerciseRecords: stubs.getExerciseRecords,
  159. getSleepRecords: stubs.getSleepRecords,
  160. getEmotionCheckinList: stubs.getEmotionCheckinList,
  161. getCheckinList: stubs.getCheckinList,
  162. getTodayTasks: stubs.getTodayTasks,
  163. reportAppEnter: stubs.reportAppEnter
  164. },
  165. // format.js 注入真实实现,保证行为契约覆盖后端真实日期形态(纯函数,无副作用)
  166. '../../utils/format.js': { parseDate: realParseDate, recordDateOf: realRecordDateOf },
  167. '@/mixins/font-scale.js': { fontScaleMixin: { data: function () { return { fontScale: 1 } }, onShow: function () {} } },
  168. '../../components/share-mixin.js': { shareMixin: {} },
  169. '../../components/LoginGuideCard.vue': {},
  170. '../../components/DimensionActivities.vue': {},
  171. '../../components/DimensionProducts.vue': {},
  172. '../../components/ArticleFeed.vue': {}
  173. }
  174. })
  175. afterEach(function () {
  176. delete globalThis.__dayGroupViewStubs
  177. })
  178. // ---------------------------------------------------------------------------
  179. // AC-1 | 状态与装配入口存在(契约新增 → 预期红)
  180. // ---------------------------------------------------------------------------
  181. describe('AC-1 日期分组状态与装配入口存在(成长主页补按日期分组 → 预期红)', function () {
  182. var component
  183. beforeEach(function () {
  184. component = loadGrowthMain().component
  185. })
  186. it('RED-A1 组件提供「日期分组状态」入口:data 字段(dateGroups/groupedRecords 之一)为数组,或 computed getter', function () {
  187. var vm = instantiate(component)
  188. var hit = DATA_FIELD_NAMES.filter(function (k) { return vm[k] !== undefined })
  189. if (hit.length > 0) {
  190. expect(Array.isArray(vm[hit[0]])).toBe(true)
  191. return
  192. }
  193. // computed getter 形式:存在且以默认 data 求值为数组
  194. var comp = component.computed || {}
  195. var cKeys = DATA_FIELD_NAMES.filter(function (k) { return typeof comp[k] === 'function' })
  196. expect(cKeys.length).toBeGreaterThan(0)
  197. expect(Array.isArray(comp[cKeys[0]].call(instantiate(component)))).toBe(true)
  198. })
  199. it('RED-A2 组件 methods 提供「按日期分组」装配方法(groupByDate 系方法存在且可调用)', function () {
  200. expect(findGroupMethodName(component)).toBeTruthy()
  201. })
  202. })
  203. // ---------------------------------------------------------------------------
  204. // AC-2 | 行为级:按日期分组装配(核心契约 → 预期红)
  205. // GREEN 契约:groupByDate(records) 把记录流按业务日期分组——
  206. // 同日合并、键 yyyy-MM-dd、多日倒序(新在前)、无有效日期平稳跳过、组内保留原记录。
  207. // ---------------------------------------------------------------------------
  208. describe('AC-2 行为级:groupByDate 系装配逻辑(契约新增 → 预期红)', function () {
  209. var component
  210. beforeEach(function () {
  211. component = loadGrowthMain().component
  212. })
  213. it('RED-A3 空记录列表 → 返回空分组数组(不抛错)', function () {
  214. expect(findGroupMethodName(component)).toBeTruthy()
  215. var groups = invokeGrouping(component, [])
  216. expect(Array.isArray(groups)).toBe(true)
  217. expect(groups.length).toBe(0)
  218. })
  219. it('RED-A4 同日记录合并为一组,分组键为 yyyy-MM-dd(混合类型:饮食 recordDate / 睡眠 sleepTime / 心情 checkinDate)', function () {
  220. expect(findGroupMethodName(component)).toBeTruthy()
  221. var groups = invokeGrouping(component, [
  222. { type: 'diet', recordDate: '2026-11-08', name: '早餐' },
  223. { type: 'sleep', sleepTime: '2026-11-08 23:00', note: '正常' },
  224. { type: 'emotion', checkinDate: '2026-11-08', mood: '平静' }
  225. ])
  226. var norm = groups.map(normalizeGroup)
  227. expect(norm.length).toBe(1)
  228. expect(norm[0].date).toBe('2026-11-08')
  229. expect(norm[0].list.length).toBe(3)
  230. })
  231. it('RED-A5 多日记录分组按日期倒序(最新在前)', function () {
  232. expect(findGroupMethodName(component)).toBeTruthy()
  233. var groups = invokeGrouping(component, sampleRecords())
  234. var dates = groups.map(normalizeGroup).map(function (g) { return g.date })
  235. expect(dates).toEqual(['2026-11-09', '2026-11-08', '2026-11-07', '2026-11-06'])
  236. })
  237. it('RED-A6 组内保留原记录对象(不丢字段、不改写输入)', function () {
  238. expect(findGroupMethodName(component)).toBeTruthy()
  239. var input = sampleRecords()
  240. var snapshot = JSON.stringify(input)
  241. var groups = invokeGrouping(component, input)
  242. var flat = []
  243. groups.map(normalizeGroup).forEach(function (g) { flat = flat.concat(g.list) })
  244. expect(input[0].recordDate).toBe('2026-11-08')
  245. expect(JSON.stringify(input)).toBe(snapshot)
  246. expect(flat).toEqual(expect.arrayContaining(input))
  247. expect(flat.length).toBe(input.length)
  248. })
  249. it('RED-A7 无有效业务日期的记录被跳过(不抛错、不产生空键分组;全无效 → 空分组)', function () {
  250. expect(findGroupMethodName(component)).toBeTruthy()
  251. var withGarbage = sampleRecords().concat([
  252. { type: 'garbage-1', checkinDate: '' },
  253. { type: 'garbage-2' },
  254. { type: 'garbage-3', checkinDate: 'not-a-date' }
  255. ])
  256. var groups = invokeGrouping(component, withGarbage)
  257. var norm = groups.map(normalizeGroup)
  258. norm.forEach(function (g) { expect(g.date).not.toBe('') })
  259. var flat = []
  260. norm.forEach(function (g) { flat = flat.concat(g.list) })
  261. expect(flat.length).toBe(6)
  262. // 全为无效记录 → 空分组
  263. expect(invokeGrouping(component, [{ checkinDate: 'bad' }, { foo: 1 }]).length).toBe(0)
  264. })
  265. })
  266. // ---------------------------------------------------------------------------
  267. // AC-3 | 结构级:模板按日期分组渲染 + 日期标题 + 空态(预期红)
  268. // ---------------------------------------------------------------------------
  269. describe('AC-3 结构级:模板按日期分组渲染与空态(变更B 验收口径:看到所有打卡记录 → 预期红)', function () {
  270. var template
  271. beforeAll(function () {
  272. // beforeAll 先于 beforeEach:仅做模板结构断言,无需桩函数
  273. globalThis.__dayGroupViewStubs = {}
  274. template = loadGrowthMain().template
  275. })
  276. it('RED-A8 模板存在「按日期分组」的记录循环渲染(v-for 数据源为 dateGroups/groupedRecords 等)', function () {
  277. expect(template).toMatch(/v-for\s*=\s*["'][^"']*(?:dateGroups|dateGroupList|groupedRecords|groupedCheckins|historyGroups|historyDays|checkinGroups|recordGroups|dayGroups|growthHistoryGroups)[^"']*["']/i)
  278. })
  279. it('RED-A9 模板存在日期分组标题渲染(分组键以 .date/.day 插值或 formatDateKey/formatRecordDate 输出)', function () {
  280. expect(template).toMatch(/v-for\s*=\s*["'][^"']*(?:dateGroups|dateGroupList|groupedRecords|groupedCheckins|historyGroups|historyDays|checkinGroups|recordGroups|dayGroups|growthHistoryGroups)[^"']*["']/i)
  281. expect(template).toMatch(/(?:formatDateKey\s*\(|formatRecordDate\s*\(|\.[dp]ate\s*[}|]|\.[dg]ay\s*[}|]|\bgroupDate\b)/)
  282. })
  283. it('RED-A10 模板存在分组空态分支:集合为空时显示空态(空态文案或 length===0 条件 v-if)', function () {
  284. var hasEmptyCopy = /暂无[\s\S]{0,10}记录|还没有[\s\S]{0,10}记录|暂无成长|暂无打卡/.test(template)
  285. var hasEmptyBranch = /v-if\s*=\s*["'][^"']*(?:dateGroups|dateGroupList|groupedRecords|groupedCheckins|historyGroups|historyDays|checkinGroups|recordGroups|dayGroups|growthHistoryGroups)[^"']*\.length\s*(?:===?)\s*0/.test(template)
  286. expect(hasEmptyCopy || hasEmptyBranch).toBe(true)
  287. })
  288. })
  289. // ---------------------------------------------------------------------------
  290. // 权限流:本能力为「家长/教师查看孩子成长与打卡历史」的成长主页按日期分组视图,
  291. // 页面在已登录态按 currentChildId 取数,无额外前端 role 门禁分支(role 校验在 JwtInterceptor 层),
  292. // 与同批 growthHistory.view.test.js 口径一致,显式记录为不适用项。
  293. // ---------------------------------------------------------------------------
  294. describe.skip('权限流:成长主页按日期分组视图无前端 role 门禁分支,不适用', function () {
  295. it('占位:该能力面向登录家长/教师,详见汇报', function () {})
  296. })