recommendation.healthAdjustUi.test.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. /**
  2. * 契约级单测(TDD-RED)——能力键 diet.food.healthAdjustUi
  3. *
  4. * 溯源:
  5. * requirement: docs/superpowers/specs/2026-11-09-diet-recommendation-health-questionnaire-adjust.md
  6. * §2 调整分级语义(blocked/warning/boost/normal)、§4 验收判据 V/C-1/6
  7. * design: 同上 §3 前端 B1-B3 + cfc-frontend/pages/diet/recommendation.vue L104-123/L285-334/L491-523
  8. *
  9. * B1. loadFoods(L491-523):/api/health/foods 响应食材透传 adjustment / adjustmentReason(旁置现有 scoreClass/statusText/status 映射)
  10. * B2. 食物卡片(L104-123):按 item.adjustment 渲染提示条——
  11. * blocked → 红条「⚠ 健康问卷不建议:{adjustmentReason}」
  12. * warning → 黄条「注意:{adjustmentReason}」
  13. * boost → 绿条「✓ 符合饮食习惯偏好」
  14. * normal/空 → 不渲染
  15. * B3. filteredFoods(L285-334):suitable Tab 中 adjustment==='blocked' 项排到列表末尾
  16. * (保持可见但不置顶);unsuitable / all 位置不变、仅带提示条;排序逻辑不变,仅 stable 分组。
  17. *
  18. * 说明(沿用既有的 Jest 体系约束,见 __tests__/family-join/join-form.required-info.test.js):
  19. * jest.config.js 仅 transform .js;约定为「加载真实 SFC 的 <script>/<template> 源码断言」,不挂载 .vue。
  20. * 本文件直接读取推荐食材页 recommendation.vue 的源码——
  21. * - <script>:import 语句替换为注入桩后求值,驱动真实 data()/methods/computed 做行为级断言;
  22. * - <template>:读取模板文本做结构契约断言(三类提示条 + adjustment 分支条件 + adjustmentReason 插值)。
  23. * GREEN 阶段实现方对 recommendation.vue 补足 B1-B3 后本文件即翻绿;当前实现缺失 → 预期 RED。
  24. * 本文件不修改 pages/ 任何业务代码。
  25. */
  26. import fs from 'fs'
  27. import path from 'path'
  28. const RECOMMENDATION_PATH = path.join(__dirname, '../../pages/diet/recommendation.vue')
  29. // ---------------------------------------------------------------------------
  30. // 工具:加载真实 recommendation.vue 的 <script> 行为(data/methods/computed)与 <template> 结构
  31. // ---------------------------------------------------------------------------
  32. /** 把 ES import 语句替换为从 globalThis.__recommendationStubs 取桩的声明(不解析模块,避免污染业务实现) */
  33. function stubImports(script, stubMap) {
  34. return script.replace(/import\s+([^;]+?)\s+from\s+['"]([^'"]+)['"];?/g, function (m, clause, id) {
  35. var names = []
  36. var c = clause.trim()
  37. var braceIdx = c.indexOf('{')
  38. if (braceIdx >= 0) {
  39. var def = c.slice(0, braceIdx).replace(/,\s*$/, '').trim()
  40. if (def) names.push(def)
  41. var named = c.slice(braceIdx + 1, c.lastIndexOf('}'))
  42. named.split(',').forEach(function (part) {
  43. var p = part.trim()
  44. if (!p) return
  45. var parts = p.split(/\s+as\s+/)
  46. var local = parts.length > 1 ? parts[1].trim() : parts[0].trim()
  47. if (local) names.push(local)
  48. })
  49. } else if (c.indexOf('*') === 0) {
  50. var nsMatch = c.match(/\*\s+as\s+(\w+)/)
  51. if (nsMatch) names.push(nsMatch[1])
  52. } else {
  53. names.push(c)
  54. }
  55. return names.map(function (n) {
  56. return 'var ' + n + ' = (globalThis.__recommendationStubs[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
  57. }).join('\n')
  58. })
  59. }
  60. /** 加载真实 SFC:返回 { component, template }(component = 真实 <script> 的 export default 对象) */
  61. function loadRecommendation() {
  62. var src = fs.readFileSync(RECOMMENDATION_PATH, 'utf8')
  63. var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
  64. var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
  65. if (!scriptMatch) throw new Error('无法在 recommendation.vue 中定位 <script> 块')
  66. var script = stubImports(scriptMatch[1], globalThis.__recommendationStubs || {})
  67. script = script.replace(/export default\s*\{/, 'module.exports = {')
  68. var mod = { exports: {} }
  69. // eslint-disable-next-line no-new-func
  70. var fn = new Function('module', 'exports', script)
  71. fn(mod, mod.exports)
  72. return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '' }
  73. }
  74. /** 依据真实组件的 data()/methods 构造可驱动上下文(模拟 Vue 合并,computed 由用例对 component.computed 调用) */
  75. function instantiate(component) {
  76. var vm = {}
  77. var data = typeof component.data === 'function' ? component.data.call(vm) : (component.data || {})
  78. Object.keys(data).forEach(function (k) { vm[k] = data[k] })
  79. var methods = component.methods || {}
  80. Object.keys(methods).forEach(function (k) { vm[k] = methods[k] })
  81. return vm
  82. }
  83. /** 驱动真实 computed.filteredFoods(computed 为函数属性,以 vm 为 this 求值) */
  84. function evalFilteredFoods(component, vm) {
  85. var computed = component.computed || {}
  86. if (typeof computed.filteredFoods !== 'function') throw new Error('computed.filteredFoods 缺失')
  87. return computed.filteredFoods.call(vm)
  88. }
  89. function ids(list) {
  90. return list.map(function (f) { return f.id })
  91. }
  92. // ---------------------------------------------------------------------------
  93. // 测试夹具
  94. // ---------------------------------------------------------------------------
  95. var stubs
  96. beforeEach(function () {
  97. global.uni._storage = {}
  98. global.uni.request.mockReset()
  99. global.uni.showToast.mockReset()
  100. stubs = {
  101. getDietRecommendation: jest.fn(function () { return Promise.resolve({ code: 0, message: 'ok', data: null }) }),
  102. generateDietRecommendation: jest.fn(),
  103. completeDietRecommendation: jest.fn(),
  104. regenerateDietRecommendation: jest.fn(),
  105. updateDietRecommendation: jest.fn(function () { return Promise.resolve({ code: 200, message: 'success', data: null }) }),
  106. config: { API_BASE_URL: 'http://mock' },
  107. MemberSelector: {},
  108. memberIdOf: function (m) { return m && (m.familyMemberId || m.memberId || m.id) },
  109. fontScaleMixin: { data: function () { return { fontScale: 1 } }, onShow: function () {} }
  110. }
  111. globalThis.__recommendationStubs = {
  112. '@/utils/api.js': {
  113. getDietRecommendation: stubs.getDietRecommendation,
  114. generateDietRecommendation: stubs.generateDietRecommendation,
  115. completeDietRecommendation: stubs.completeDietRecommendation,
  116. regenerateDietRecommendation: stubs.regenerateDietRecommendation,
  117. updateDietRecommendation: stubs.updateDietRecommendation
  118. },
  119. '@/config.js': { config: stubs.config },
  120. '@/components/MemberSelector.vue': { MemberSelector: stubs.MemberSelector },
  121. '@/utils/memberNormalize.js': { memberIdOf: stubs.memberIdOf },
  122. '@/mixins/font-scale.js': { fontScaleMixin: stubs.fontScaleMixin }
  123. }
  124. })
  125. afterEach(function () {
  126. delete globalThis.__recommendationStubs
  127. })
  128. // ---------------------------------------------------------------------------
  129. // B1. loadFoods 透传 adjustment / adjustmentReason(旁置现有 scoreClass/statusText/status 映射)
  130. // 契约:/api/health/foods 响应食材的 adjustment / adjustmentReason 必须原样进入 allFoods,
  131. // 不得被 map 丢弃或改写(GREEN 实现须保持显式透传;当前借 object 复用保留,属既有增强面)
  132. // ---------------------------------------------------------------------------
  133. describe('B1 loadFoods 透传 adjustment / adjustmentReason', function () {
  134. var component
  135. beforeEach(function () {
  136. component = loadRecommendation().component
  137. global.uni._storage.token = 'mock-token'
  138. })
  139. it('后端返回 adjustment=blocked 食材 → allFoods 保留 blocked 与 adjustmentReason 原文', function () {
  140. var foods = [{ id: 1, name: '花生', category: '谷物', score: 8, adjustment: 'blocked', adjustmentReason: '过敏原花生命中,建议不食' }]
  141. global.uni.request.mockImplementation(function (opts) {
  142. opts.success({ data: { code: 200, data: foods } })
  143. })
  144. var vm = instantiate(component)
  145. vm.loadFoods()
  146. expect(vm.allFoods.length).toBe(1)
  147. expect(vm.allFoods[0].adjustment).toBe('blocked')
  148. expect(vm.allFoods[0].adjustmentReason).toBe('过敏原花生命中,建议不食')
  149. })
  150. it('后端返回 adjustment=warning 食材 → allFoods 保留 warning 与 interval 提示文案', function () {
  151. var foods = [{ id: 2, name: '西柚', category: '水果', score: 3, adjustment: 'warning', adjustmentReason: '药物二甲双胍与西柚需间隔 30 分钟' }]
  152. global.uni.request.mockImplementation(function (opts) {
  153. opts.success({ data: { code: 200, data: foods } })
  154. })
  155. var vm = instantiate(component)
  156. vm.loadFoods()
  157. expect(vm.allFoods[0].adjustment).toBe('warning')
  158. expect(vm.allFoods[0].adjustmentReason).toBe('药物二甲双胍与西柚需间隔 30 分钟')
  159. })
  160. it('后端未返回 adjustment(报告快照分支/灰度未下发)→ allFoods 不伪造 adjustment 值', function () {
  161. var foods = [{ id: 3, name: '苹果', category: '水果', score: 6 }]
  162. global.uni.request.mockImplementation(function (opts) {
  163. opts.success({ data: { code: 200, data: foods } })
  164. })
  165. var vm = instantiate(component)
  166. vm.loadFoods()
  167. // normal/空 → 不渲染分支的输入前提:缺失时保持 undefined,不得擅自赋值 blocked/warning/boost
  168. expect(vm.allFoods[0].adjustment).toBeUndefined()
  169. expect(vm.allFoods[0].adjustmentReason).toBeUndefined()
  170. })
  171. it('既有 scoreClass/statusText/status 映射无回归', function () {
  172. var foods = [{ id: 4, name: '鸡蛋', category: '蛋奶', score: 10, adjustment: 'boost' }]
  173. global.uni.request.mockImplementation(function (opts) {
  174. opts.success({ data: { code: 200, data: foods } })
  175. })
  176. var vm = instantiate(component)
  177. vm.loadFoods()
  178. expect(vm.allFoods[0].scoreClass).toBe('good')
  179. expect(vm.allFoods[0].statusText).toBe('适合')
  180. expect(vm.allFoods[0].status).toBe('suitable')
  181. })
  182. })
  183. // ---------------------------------------------------------------------------
  184. // B2. 食物卡片按 item.adjustment 渲染三类提示条(template 结构契约,当前实现缺失 → 预期 RED)
  185. // blocked → 红条「⚠ 健康问卷不建议:{adjustmentReason}」
  186. // warning → 黄条「注意:{adjustmentReason}」
  187. // boost → 绿条「✓ 符合饮食习惯偏好」
  188. // normal/空 → 不渲染(无独立分支,仅 v-if 缺席判定)
  189. // ---------------------------------------------------------------------------
  190. describe('B2 食物卡片 adjustment 提示条(template 结构契约)', function () {
  191. var template
  192. beforeAll(function () {
  193. // beforeAll 先于 beforeEach:仅做模板结构断言,无需桩函数,置空即可(loadRecommendation 对桩做可选访问)
  194. globalThis.__recommendationStubs = {}
  195. template = loadRecommendation().template
  196. })
  197. it('blocked:红条「健康问卷不建议」以 item.adjustment === blocked 为条件', function () {
  198. expect(template).toMatch(/健康问卷不建议/)
  199. expect(template).toMatch(/item\.adjustment\s*===?\s*'blocked'/)
  200. })
  201. it('blocked 红条插值渲染 adjustmentReason(原因为空则不渲染该文案)', function () {
  202. expect(template).toMatch(/item\.adjustmentReason/)
  203. })
  204. it('warning:黄条「注意」以 item.adjustment === warning 为条件', function () {
  205. expect(template).toMatch(/注意/)
  206. expect(template).toMatch(/item\.adjustment\s*===?\s*'warning'/)
  207. })
  208. it('boost:绿条「符合饮食习惯偏好」以 item.adjustment === boost 为条件', function () {
  209. expect(template).toMatch(/符合饮食习惯偏好/)
  210. expect(template).toMatch(/item\.adjustment\s*===?\s*'boost'/)
  211. })
  212. it('提示条仅挂在 adjustment 判定之下(normal/空不渲染:模板中不得出现无条件提示文案)', function () {
  213. // 三个提示文案若缺 v-if 条件(如直接常显),将同时命中「无条件常显」:此处抽样断言文案与条件在卡片域内共存。
  214. var cardRegion = template.split('<view class="food-card"')[1] || ''
  215. expect(cardRegion).toMatch(/item\.adjustment/)
  216. })
  217. })
  218. // ---------------------------------------------------------------------------
  219. // B3. filteredFoods 分组:suitable Tab 中 blocked 项排到列表末尾(当前仅按 score 排序 → 预期 RED)
  220. // unsuitable / all:位置不变,仅带提示条(既有 score 排序无回归锁定)
  221. // ---------------------------------------------------------------------------
  222. describe('B3 filteredFoods 分组(suitable blocked 排末尾)', function () {
  223. function makeVm(component) {
  224. var vm = instantiate(component)
  225. vm.currentView = 'personal'
  226. vm.activeCategory = 'all'
  227. vm.searchQuery = ''
  228. return vm
  229. }
  230. it('suitable + desc:非 blocked 按分值在前,blocked 高值项落列表末尾(不置顶)', function () {
  231. var component = loadRecommendation().component
  232. var vm = makeVm(component)
  233. vm.filterType = 'suitable'
  234. vm.sortType = 'desc'
  235. vm.allFoods = [
  236. { id: 1, name: '鸡蛋', category: '蛋奶', score: 3, adjustment: 'boost' },
  237. { id: 2, name: '花生', category: '谷物', score: 10, adjustment: 'blocked', adjustmentReason: '过敏原花生命中,建议不食' },
  238. { id: 3, name: '牛奶', category: '蛋奶', score: 5, adjustment: 'normal' }
  239. ]
  240. var result = evalFilteredFoods(component, vm)
  241. // 契约:花生(blocked) 虽分值最高,仍排末尾 → [牛奶, 鸡蛋, 花生]
  242. expect(ids(result)).toEqual([3, 1, 2])
  243. })
  244. it('suitable Tab 首项不得为 blocked(存在非 blocked 可排时)', function () {
  245. var component = loadRecommendation().component
  246. var vm = makeVm(component)
  247. vm.filterType = 'suitable'
  248. vm.sortType = 'desc'
  249. vm.allFoods = [
  250. { id: 1, name: '鸡蛋', category: '蛋奶', score: 3, adjustment: 'boost' },
  251. { id: 2, name: '花生', category: '谷物', score: 10, adjustment: 'blocked', adjustmentReason: '过敏原花生命中,建议不食' },
  252. { id: 3, name: '牛奶', category: '蛋奶', score: 5, adjustment: 'normal' }
  253. ]
  254. var result = evalFilteredFoods(component, vm)
  255. expect(result[0].adjustment).not.toBe('blocked')
  256. })
  257. it('suitable + desc:多个 blocked 项整体落末尾(stable 分组,组内保持分值序)', function () {
  258. var component = loadRecommendation().component
  259. var vm = makeVm(component)
  260. vm.filterType = 'suitable'
  261. vm.sortType = 'desc'
  262. vm.allFoods = [
  263. { id: 1, name: '鸡蛋', category: '蛋奶', score: 9, adjustment: 'boost' },
  264. { id: 2, name: '花生', category: '谷物', score: 8, adjustment: 'blocked', adjustmentReason: '过敏原花生命中,建议不食' },
  265. { id: 3, name: '核桃', category: '坚果', score: 7, adjustment: 'blocked', adjustmentReason: '疾病痛风禁忌食用' },
  266. { id: 4, name: '苹果', category: '水果', score: 6, adjustment: undefined }
  267. ]
  268. var result = evalFilteredFoods(component, vm)
  269. // 非 blocked 在前(鸡蛋9 > 苹果6),blocked 组整体落末尾(花生8 > 核桃7)
  270. expect(ids(result)).toEqual([1, 4, 2, 3])
  271. })
  272. it('unsuitable Tab:blocked 不强制移动,仅按既有分值排序(位置不变、仅带提示条)', function () {
  273. var component = loadRecommendation().component
  274. var vm = makeVm(component)
  275. vm.filterType = 'unsuitable'
  276. vm.sortType = 'asc'
  277. vm.allFoods = [
  278. { id: 1, name: '动物内脏', category: '肉禽', score: -5, adjustment: 'blocked', adjustmentReason: '疾病痛风禁忌食用' },
  279. { id: 2, name: '西柚', category: '水果', score: -8, adjustment: 'warning', adjustmentReason: '药物间隔离提示' },
  280. { id: 3, name: '腌制菜', category: '蔬菜', score: -3, adjustment: 'normal' }
  281. ]
  282. var result = evalFilteredFoods(component, vm)
  283. // 升序:西柚(-8) < 动物内脏(-5) < 腌制菜(-3),blocked 不置末
  284. expect(ids(result)).toEqual([2, 1, 3])
  285. })
  286. it('all Tab:位置不变、仅带提示条(既有 score 排序无回归)', function () {
  287. var component = loadRecommendation().component
  288. var vm = makeVm(component)
  289. vm.filterType = 'all'
  290. vm.sortType = 'desc'
  291. vm.allFoods = [
  292. { id: 1, name: '鸡蛋', category: '蛋奶', score: 9, adjustment: 'boost' },
  293. { id: 2, name: '花生', category: '谷物', score: 8, adjustment: 'blocked', adjustmentReason: '过敏原花生命中,建议不食' },
  294. { id: 4, name: '苹果', category: '水果', score: 6, adjustment: undefined }
  295. ]
  296. var result = evalFilteredFoods(component, vm)
  297. expect(ids(result)).toEqual([1, 2, 4])
  298. })
  299. })
  300. // ---------------------------------------------------------------------------
  301. // 权限流:本能力为「当前推荐」个人食材视图的展示层(recommendation.vue),
  302. // 页面沿既有 JWT/memberId 鉴权(controller 侧 userId/familyId 属性鉴权,接口不新增越权面),
  303. // 前端无独立角色分支 → 《编排派发》中「权限(适用时)」的不适用项,显式记录。
  304. // ---------------------------------------------------------------------------
  305. describe.skip('权限流:健康问卷调整展示无独立角色门禁,不适用', function () {
  306. it('占位:该能力沿既有 memberId/userId 鉴权,无新增 role 分支(详见汇报)', function () {})
  307. })