Browse Source

test(cfc-frontend): S-cfc-421 health.frontend.guheV2Display 契约 RED 单测

谷禾新版解析与五维归因升级方案 P1-3 前端展示增强契约级单测。
报告详情页异常菌清单卡片/亚健康诊断标签 + 健康计划页免责声明均未落地,
预期 RED(14 failed / 2 passed)。仅新增测试文件,零 src/main 改动。
Administrator 2 days ago
parent
commit
fdbf4a3f14

+ 316 - 0
cfc-frontend/__tests__/pages/health/health-guhe-v2-display.contract.test.js

@@ -0,0 +1,316 @@
+/**
+ * 契约级单测(TDD-RED)——能力键 health.frontend.guheV2Display(P1-3 前端展示增强)
+ *
+ * 溯源:
+ *   requirement: tests/user-scenarios/应用场景总览.md  SC-P-22(报告解析预览,入库前核对)
+ *   design:      docs/浠艾福程序-谷禾新版解析与五维归因升级方案-v1.0.md
+ *                §三 P1-3(前端展示增强:报告详情页「异常菌清单」卡片 ↑↓ 分组 12 条、
+ *                          报告详情页「亚健康诊断」标签、健康计划页底部固定免责声明 §8.8 红线)
+ *                §六 6.2(GET /api/health/report/detail 响应新增 abnormalSpecies / speciesLibrary /
+ *                        fbRatio / shannonIndexNorm / subhealthLabel / parseSelfCheck)
+ *
+ * 说明(既有 Jest 体系约束,沿用 __tests__/family-join/join-form.required-info.test.js 约定):
+ *   - jest.config.js 仅 transform `.js`(babel-jest),moduleFileExtensions 不含 `vue`,
+ *     未安装 vue-jest/jsdom 组件环境 —— 既有约定为「加载真实 SFC 的 <script>/<template> 断言」。
+ *   - <script>:把 import 语句替换为注入桩后求值,得到真实组件的 data()/methods,做行为级断言;
+ *   - <template>:读取模板文本,做结构契约断言(异常菌清单卡片、亚健康诊断标签、免责声明)。
+ *   - 若实现方在后续 GREEN 阶段对 report-detail.vue / health-plan-summary.vue 补足契约,
+ *     本文件断言即翻绿;当前实现缺失 → 预期 RED。
+ *   - 本文件不修改 pages/、utils/ 任何业务代码。
+ *
+ * 设计文档所述 pages/health-report、pages/attribution 路径与实际 cfc-frontend 不符:
+ *   实际为 cfc-frontend/pages/health(report-detail.vue、health-plan-summary.vue),
+ *   以实现时探测为准,本文件按探测到的真实路径加载。
+ *   归因页「菌群 → 五维」可视化(内联 SVG 相生相克图)当前 cfc-frontend 无对应页面,
+ *   不在此文件硬断言(组件路径不存在会报错而非红测),以探测到的 report-detail /
+ *   health-plan-summary 两个已存在页面的契约展示为准。
+ */
+
+import fs from 'fs'
+import path from 'path'
+import { getReportDetail as apiGetReportDetail, clearApiDedup } from '@/utils/api'
+
+const REPORT_DETAIL_PATH = path.join(__dirname, '../../../pages/health/report-detail.vue')
+const HEALTH_PLAN_PATH = path.join(__dirname, '../../../pages/health/health-plan-summary.vue')
+
+// ---------------------------------------------------------------------------
+// 工具:加载真实 SFC 的 <script> 逻辑(行为级)与 <template> 结构(结构级)
+// ---------------------------------------------------------------------------
+
+/** 把 ES import 语句替换为从 globalThis.__stubs 取桩的声明(不解析模块,避免污染业务实现) */
+function stubImports(script, stubMap) {
+  return script.replace(/import\s+([^;]+?)\s+from\s+['"]([^'"]+)['"];?/g, function (m, clause, id) {
+    var names = []
+    var c = clause.trim()
+    var braceIdx = c.indexOf('{')
+    if (braceIdx >= 0) {
+      var def = c.slice(0, braceIdx).replace(/,\s*$/, '').trim()
+      if (def) names.push(def)
+      var named = c.slice(braceIdx + 1, c.lastIndexOf('}'))
+      named.split(',').forEach(function (part) {
+        var p = part.trim()
+        if (!p) return
+        var parts = p.split(/\s+as\s+/)
+        var local = parts.length > 1 ? parts[1].trim() : parts[0].trim()
+        if (local) names.push(local)
+      })
+    } else if (c.indexOf('*') === 0) {
+      var nsMatch = c.match(/\*\s+as\s+(\w+)/)
+      if (nsMatch) names.push(nsMatch[1])
+    } else {
+      names.push(c)
+    }
+    return names.map(function (n) {
+      return 'var ' + n + ' = (globalThis.__guheStubs[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 加载真实 SFC:返回 { component, template }(component = 真实 <script> 的 export default 对象) */
+function loadSfc(filePath) {
+  var src = fs.readFileSync(filePath, 'utf8')
+  var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!scriptMatch) throw new Error('无法在 ' + filePath + ' 中定位 <script> 块')
+  var script = stubImports(scriptMatch[1], globalThis.__guheStubs || {})
+  script = script.replace(/export default\s*\{/, 'module.exports = {')
+  var mod = { exports: {} }
+  // eslint-disable-next-line no-new-func
+  var fn = new Function('module', 'exports', script)
+  fn(mod, mod.exports)
+  return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '' }
+}
+
+/** 依据真实组件的 data()/methods 构造可驱动上下文(模拟 Vue 把 data 与 methods 合并到实例) */
+function instantiate(component) {
+  var vm = {}
+  var data = typeof component.data === 'function' ? component.data.call(vm) : (component.data || {})
+  Object.keys(data).forEach(function (k) { vm[k] = data[k] })
+  var methods = component.methods || {}
+  Object.keys(methods).forEach(function (k) { vm[k] = methods[k] })
+  return vm
+}
+
+// ---------------------------------------------------------------------------
+// 测试夹具
+// ---------------------------------------------------------------------------
+
+var stubs
+
+beforeEach(function () {
+  global.uni._storage = {}
+  global.uni.showToast.mockReset()
+  global.uni.showLoading.mockReset()
+  global.uni.hideLoading.mockReset()
+  stubs = {
+    getReportDetail: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    getReportIndicators: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: { items: [] } }) }),
+    getDanReportDetail: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    getReportPayload: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    editHealthReport: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    parseReportDraft: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    confirmReportPreview: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    discardReportDraft: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    confirmTongue: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    discardTongue: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    getFamilyMemberList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
+    addFamilyMember: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    queryIndicatorKnowledge: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    queryBacteriaKnowledge: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }),
+    normalizeMembers: jest.fn(function (arr) { return arr || [] }),
+    memberIdOf: jest.fn(function (m) { return m ? (m.id != null ? m.id : m.memberId) : null }),
+    resolveChange: jest.fn(function () { return { trendLabel: '', cssClass: 'flat', arrow: '', colorClass: 'gray-text', showArrow: false } }),
+    formatDate: jest.fn(function (v) { return v ? String(v).substring(0, 10) : '' }),
+    fontScaleMixin: { data: function () { return { fontScale: 1 } }, onShow: function () {} },
+    ReportBlocksRenderer: { name: 'ReportBlocksRenderer' },
+    FeedbackPopup: { name: 'FeedbackPopup' },
+    IndicatorChangeRow: { name: 'IndicatorChangeRow' }
+  }
+  globalThis.__guheStubs = {
+    '../../utils/api.js': {
+      getReportDetail: stubs.getReportDetail,
+      getDanReportDetail: stubs.getDanReportDetail,
+      getReportPayload: stubs.getReportPayload,
+      editHealthReport: stubs.editHealthReport,
+      parseReportDraft: stubs.parseReportDraft,
+      confirmReportPreview: stubs.confirmReportPreview,
+      discardReportDraft: stubs.discardReportDraft,
+      confirmTongue: stubs.confirmTongue,
+      discardTongue: stubs.discardTongue,
+      getFamilyMemberList: stubs.getFamilyMemberList,
+      addFamilyMember: stubs.addFamilyMember,
+      queryIndicatorKnowledge: stubs.queryIndicatorKnowledge,
+      queryBacteriaKnowledge: stubs.queryBacteriaKnowledge,
+      getReportIndicators: stubs.getReportIndicators
+    },
+    '../../utils/memberNormalize.js': { normalizeMembers: stubs.normalizeMembers, memberIdOf: stubs.memberIdOf },
+    '@/utils/indicator-change': { resolveChange: stubs.resolveChange },
+    '../../utils/format.js': { formatDate: stubs.formatDate },
+    '@/mixins/font-scale.js': { fontScaleMixin: stubs.fontScaleMixin },
+    './report-blocks-renderer.vue': { default: stubs.ReportBlocksRenderer, ReportBlocksRenderer: stubs.ReportBlocksRenderer },
+    '@/pages/health/components/feedback-popup.vue': { default: stubs.FeedbackPopup, FeedbackPopup: stubs.FeedbackPopup },
+    '@/pages/health/components/IndicatorChangeRow.vue': { default: stubs.IndicatorChangeRow, IndicatorChangeRow: stubs.IndicatorChangeRow }
+  }
+})
+
+afterEach(function () {
+  delete globalThis.__guheStubs
+})
+
+// ---------------------------------------------------------------------------
+// §6.2 接口契约 → report-detail.vue 消费:详情响应新增 guhe_v2 字段应写入组件状态
+// (P1-3 展示依赖 P0-4/P0-6;前端消费这些字段是「可显示、可干预」契约的前提)
+// ---------------------------------------------------------------------------
+
+describe('§6.2 report-detail.vue 消费详情接口新增 guhe_v2 字段', function () {
+  var component
+  beforeEach(function () { component = loadSfc(REPORT_DETAIL_PATH).component })
+
+  it('响应含 abnormalSpecies 数组 → 组件状态写入(异常菌清单数据源)', async function () {
+    var detail = {
+      report: { reportFormat: 'guhe_v2', subjectId: 1 },
+      payload: {},
+      abnormalSpecies: [
+        { speciesNo: 1, cnName: '拟杆菌属', latinName: 'Bacteroides', direction: '↓', abundance: '12%', refRange: '20-40%', category: '条件致病菌', populationLevel: '偏低' },
+        { speciesNo: 2, cnName: '大肠埃希菌', latinName: 'Escherichia coli', direction: '↑', abundance: '30%', refRange: '1-5%', category: '条件致病菌', populationLevel: '偏高' }
+      ]
+    }
+    stubs.getReportDetail.mockResolvedValue({ code: 200, message: 'ok', data: detail })
+    var vm = instantiate(component)
+    vm.reportId = 123
+    await vm.loadData()
+    expect(vm.abnormalSpecies).toEqual(detail.abnormalSpecies)
+  })
+
+  it('响应含 speciesLibrary 数组 → 组件状态写入(物种功能库数据源)', async function () {
+    var detail = {
+      report: { reportFormat: 'guhe_v2', subjectId: 1 },
+      payload: {},
+      speciesLibrary: [
+        { speciesNo: 1, cnName: '双歧杆菌', functionTag: '产丁酸', detectionRate: '高' }
+      ]
+    }
+    stubs.getReportDetail.mockResolvedValue({ code: 200, message: 'ok', data: detail })
+    var vm = instantiate(component)
+    vm.reportId = 123
+    await vm.loadData()
+    expect(vm.speciesLibrary).toEqual(detail.speciesLibrary)
+  })
+
+  it('响应含 subhealthLabel → 组件状态写入(亚健康诊断标签)', async function () {
+    var detail = { report: { reportFormat: 'guhe_v2', subjectId: 1 }, payload: {}, subhealthLabel: '亚健康及营养膳食不合理' }
+    stubs.getReportDetail.mockResolvedValue({ code: 200, message: 'ok', data: detail })
+    var vm = instantiate(component)
+    vm.reportId = 123
+    await vm.loadData()
+    expect(vm.subhealthLabel).toBe('亚健康及营养膳食不合理')
+  })
+
+  it('响应含 fbRatio → 组件状态写入(F/B 比值)', async function () {
+    var detail = { report: { reportFormat: 'guhe_v2', subjectId: 1 }, payload: {}, fbRatio: '1.35' }
+    stubs.getReportDetail.mockResolvedValue({ code: 200, message: 'ok', data: detail })
+    var vm = instantiate(component)
+    vm.reportId = 123
+    await vm.loadData()
+    expect(vm.fbRatio).toBe('1.35')
+  })
+
+  it('响应含 shannonIndexNorm → 组件状态写入(菌群多样性评级)', async function () {
+    var detail = { report: { reportFormat: 'guhe_v2', subjectId: 1 }, payload: {}, shannonIndexNorm: '中等' }
+    stubs.getReportDetail.mockResolvedValue({ code: 200, message: 'ok', data: detail })
+    var vm = instantiate(component)
+    vm.reportId = 123
+    await vm.loadData()
+    expect(vm.shannonIndexNorm).toBe('中等')
+  })
+
+  it('响应含 parseSelfCheck → 组件状态写入(解析自检 JSON)', async function () {
+    var detail = { report: { reportFormat: 'guhe_v2', subjectId: 1 }, payload: {}, parseSelfCheck: { 通过: true, P0: 0, P1: 2 } }
+    stubs.getReportDetail.mockResolvedValue({ code: 200, message: 'ok', data: detail })
+    var vm = instantiate(component)
+    vm.reportId = 123
+    await vm.loadData()
+    expect(vm.parseSelfCheck).toEqual(detail.parseSelfCheck)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// P1-3 报告详情页结构契约:「异常菌清单」卡片(↑↓ 分组展示 12 条)+「亚健康诊断」标签
+// ---------------------------------------------------------------------------
+
+describe('P1-3 report-detail.vue 模板结构:异常菌清单 + 亚健康诊断', function () {
+  var template
+  beforeAll(function () {
+    // beforeAll 先于 beforeEach:仅做模板结构断言,无需桩函数,置空即可
+    globalThis.__guheStubs = {}
+    template = loadSfc(REPORT_DETAIL_PATH).template
+  })
+
+  it('含「异常菌清单」卡片标题(入库前核对 12 条 ↑↓ 分组)', function () {
+    expect(template).toMatch(/异常菌清单/)
+  })
+
+  it('模板绑定 abnormalSpecies 数据源(v-for 遍历)', function () {
+    expect(template).toMatch(/abnormalSpecies/)
+  })
+
+  it('异常菌条目含方向分组(↑/↓ 超界标记)', function () {
+    expect(template).toMatch(/direction/)
+  })
+
+  it('异常菌条目点击展开显示丰度 / 参考范围 / 功能描述', function () {
+    // 点击展开:模板含 abundance / refRange / functionDesc(或 functionDesc 对应字段)任一绑定
+    expect(template).toMatch(/abundance|refRange|functionDesc|functionTag|function_desc/)
+  })
+
+  it('含「亚健康诊断」标签(如「亚健康及营养膳食不合理」)', function () {
+    expect(template).toMatch(/亚健康诊断/)
+  })
+
+  it('亚健康诊断标签绑定 subhealthLabel', function () {
+    expect(template).toMatch(/subhealthLabel/)
+  })
+
+  it('含 F/B 比值展示(fbRatio 绑定)', function () {
+    expect(template).toMatch(/fbRatio/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// P1-3 健康计划页结构契约:底部固定免责声明(§8.8 红线:相关关联非因果、测试 ≠ 诊断)
+// ---------------------------------------------------------------------------
+
+describe('P1-3 health-plan-summary.vue 模板结构:底部固定免责声明', function () {
+  var template
+  beforeAll(function () {
+    globalThis.__guheStubs = {}
+    template = loadSfc(HEALTH_PLAN_PATH).template
+  })
+
+  it('含免责声明文案(不构成医学诊断 / 相关关联非因果)', function () {
+    expect(template).toMatch(/免责声明|不构成医学诊断|不做诊断|非因果|仅供参考|相关关联/)
+  })
+
+  it('免责声明区域固定底部(fixed 定位或 bottom 容器)', function () {
+    expect(template).toMatch(/免责|disclaimer/i)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 设计锚点:utils/api.js getReportDetail 透传 reportId(§6.2 接口既有封装,防回归锚点)
+// ---------------------------------------------------------------------------
+
+describe('设计锚点:api.js getReportDetail 透传 reportId', function () {
+  it('POST /api/health/report/detail 请求体含 reportId', async function () {
+    var captured = null
+    global.uni.request.mockImplementation(function (opts) {
+      captured = opts
+      process.nextTick(function () { opts.success({ data: { code: 200, message: 'ok', data: null } }) })
+    })
+    clearApiDedup()
+    await apiGetReportDetail(123)
+    expect(captured.url).toContain('/api/health/report/detail')
+    expect(captured.method).toBe('POST')
+    expect(captured.data).toEqual(expect.objectContaining({ reportId: 123 }))
+  })
+})