Browse Source

test(ai.aiyunyi.reportDetail): S-cfc-457 TDD-RED 契约单测(报告详情页,预期红)

Agnes Agent 4 hours ago
parent
commit
8acf5ac276

+ 403 - 0
cfc-frontend/__tests__/pages/health/aiyunyi.reportDetail.contract.test.js

@@ -0,0 +1,403 @@
+/**
+ * 契约级单测(TDD-RED)——能力键 ai.aiyunyi.reportDetail(任务 S-cfc-457)
+ *
+ * 溯源:
+ *   requirement: docs/2026-11-24-爱云医AI检测接入方案.md
+ *                §4.2(新增 pages/health/ai-report-detail.vue:爱云医报告结果展示,
+ *                      一期按爱云医原始结构渲染,二期再映射五维)、
+ *                §8「前端验收」第 2 条(选素材上传 → 进度面板「识别中」→ 完成后跳报告详情)
+ *   design:      docs/2026-11-24-爱云医AI检测接入方案.md
+ *                §4.2(原始结构渲染,二期映射五维;utils/api.js 新增 aiyunyi.getReport 封装)、
+ *                §4.5(R3:报告分页接口缺陷 1011011002 → 报告只走 report/get 按 id 拉取,
+ *                      报告 id 从套餐用户信息/映射表取,不走 report/page)、
+ *                附录 A.6(report/get 响应 data.reportDiseaseRespList[].diseaseDetailList[]:
+ *                         diseaseDetailName/Cn、accuracy、diseaseLevel;accuracy 空 → 参考值提示,
+ *                         diseaseLevel 空 → 「未检出」,不要自行填 0)
+ *
+ * 说明(既有 Jest 体系约束,风格对齐 __tests__/family-join/join-form.required-info.test.js
+ *   与同批已合入 RED 用例 __tests__/pages/health/aiyunyi.detectPage.contract.test.js):
+ *   - jest.config.js testEnvironment=node,无 vue-jest/jsdom 组件环境;既有约定为
+ *     「直接加载真实 SFC 源码做断言」:<script> 注入桩求值取 data()/methods 做行为断言,
+ *     <template> 取模板文本做结构断言。
+ *   - 当前状态:ai-report-detail.vue、pages.json 路由、api.js 的 aiyunyi.getReport 均未落地
+ *     → 预期 RED。GREEN 阶段按本文件锚定的契约补足实现后断言应可翻绿。
+ *   - 本文件只新增 __tests__ 下的测试,不修改任何 pages/、utils/ 业务实现。
+ */
+
+import fs from 'fs'
+import path from 'path'
+
+// __tests__/pages/health → ../../.. = cfc-frontend 根目录
+const ROOT = path.join(__dirname, '../../..')
+
+const DETAIL_PATH = path.join(ROOT, 'pages/health/ai-report-detail.vue')
+const API_PATH = path.join(ROOT, 'utils/api.js')
+const PAGES_JSON_PATH = path.join(ROOT, 'pages.json')
+
+/** 缺失实现时返回空源:后续断言按「契约缺失」失败(RED),避免 hook 抛错噪音;AC-R0 单独断言文件存在 */
+function readDetailSource() {
+  if (!fs.existsSync(DETAIL_PATH)) return ''
+  return fs.readFileSync(DETAIL_PATH, 'utf8')
+}
+
+// ---------------------------------------------------------------------------
+// 工具:加载真实 SFC(行为级 <script> + 结构级 <template>),风格对齐 family-join
+// ---------------------------------------------------------------------------
+
+/** 把 ES import 改为从 globalThis[stubKey] 取桩(不解析模块,避免污染业务实现) */
+function stubImports(script, moduleStubs, stubKey) {
+  globalThis[stubKey] = moduleStubs
+  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[' + JSON.stringify(stubKey) + '][' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 通用 SFC 加载器 */
+function makeSfcLoader(stubKey, getStubs) {
+  return function loadSfc(filePath) {
+    var src = readDetailSource()
+    var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+    var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+    // 实现未落地时返回空组件/空模板,让各用例以「契约缺失」失败(RED),而非 hook 抛错
+    if (!scriptMatch) return { component: {}, template: '', source: src }
+    var script = stubImports(scriptMatch[1], getStubs(), stubKey)
+    script = script.replace(/export default\s*\{/, 'module.exports = {')
+    var mod = { exports: {} }
+    // eslint-disable-next-line no-new-func
+    new Function('module', 'exports', script)(mod, mod.exports)
+    return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '', source: src }
+  }
+}
+
+/** 模拟 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
+}
+
+/** 报告原始结构夹具(附录 A.6) */
+var RAW_REPORT = {
+  reportDiseaseRespList: [
+    {
+      diseaseName: '心血管风险',
+      diseaseDetailList: [
+        { diseaseDetailName: 'CRP', diseaseDetailNameCn: 'C反应蛋白', accuracy: '8.2', diseaseLevel: '偏高' },
+        { diseaseDetailName: 'HDL', diseaseDetailNameCn: '高密度脂蛋白', accuracy: '', diseaseLevel: '' }
+      ]
+    }
+  ]
+}
+
+// ---------------------------------------------------------------------------
+// 测试夹具:为 GREEN 阶段可能存在的 import 预留桩;getReport 与 report/page 分开计数
+// ---------------------------------------------------------------------------
+
+var getReportSpy
+var reportPageSpy
+var genericApiSpy
+
+function buildModuleStubs() {
+  var ok = function () { return Promise.resolve({ code: 200, message: 'ok', data: null }) }
+  getReportSpy = jest.fn(ok)
+  reportPageSpy = jest.fn(ok)
+  genericApiSpy = jest.fn(ok)
+
+  function spyForName(name) {
+    name = String(name)
+    // §4.5 R3:任何 report/page / report/list / report/summary 类调用都是「不走 report/get」的错误分支
+    if (/report/i.test(name) && /page|list|summary/i.test(name)) return reportPageSpy
+    if (/report/i.test(name)) return getReportSpy
+    return genericApiSpy
+  }
+
+  // 命名空间:aiyunyi.getReport(id);同时兼容 aiyunyiGetReport / 平铺 getReport
+  var aiyunyiNamespace = new Proxy({}, {
+    get: function (target, prop) {
+      if (typeof prop === 'symbol') return undefined
+      return spyForName(prop)
+    }
+  })
+  var apiModule = new Proxy({}, {
+    get: function (target, prop) {
+      if (typeof prop === 'symbol') return undefined
+      if (prop === 'aiyunyi') return aiyunyiNamespace
+      return spyForName(prop)
+    }
+  })
+
+  return {
+    '@/utils/api.js': apiModule,
+    '../../utils/api.js': apiModule,
+    '@/utils/format.js': { formatDate: function (v) { return v ? String(v).substring(0, 10) : '' } },
+    '@/mixins/font-scale.js': {
+      fontScaleMixin: { data: function () { return { fontScale: 1 } }, onShow: function () {} }
+    }
+  }
+}
+
+var loadDetail = makeSfcLoader('__aiyunyiReportDetailStubs', buildModuleStubs)
+
+/** 等待 Promise.then 链落定(微任务) */
+function flush() {
+  return new Promise(function (resolve) { process.nextTick(resolve) })
+}
+
+/** 汇总页面上「用户可见」的提示文案:组件状态 + toast + modal */
+function visibleMessage(vm) {
+  var parts = []
+  ;['emptyText', 'errorMessage', 'errorText', 'statusText', 'generatingText', 'message', 'hint'].forEach(function (k) {
+    if (vm[k]) parts.push(String(vm[k]))
+  })
+  global.uni.showToast.mock.calls.forEach(function (c) { parts.push((c[0] && c[0].title) || '') })
+  global.uni.showModal.mock.calls.forEach(function (c) { parts.push(JSON.stringify(c[0] || {})) })
+  return parts.join(' ')
+}
+
+beforeEach(function () {
+  global.uni._storage = {}
+  ;['showToast', 'showModal', 'showLoading', 'hideLoading', 'navigateTo', 'redirectTo', 'request'].forEach(function (k) {
+    if (global.uni[k] && global.uni[k].mockReset) global.uni[k].mockReset()
+  })
+  buildModuleStubs()
+})
+
+afterEach(function () {
+  delete globalThis.__aiyunyiReportDetailStubs
+})
+
+// ===========================================================================
+// AC-R0 报告详情页文件存在性(本能力 TDD-RED 主红信号:实现未落地 → 文件缺失)
+// ===========================================================================
+
+describe('AC-R0 报告详情页文件存在性契约', function () {
+  it('pages/health/ai-report-detail.vue 必须存在(§4.2 新增页面)', function () {
+    expect(fs.existsSync(DETAIL_PATH)).toBe(true)
+  })
+})
+
+// ===========================================================================
+// AC-R1 pages.json 路由注册(§4.2:完成后跳转报告详情)
+// ===========================================================================
+
+describe('AC-R1 pages.json 报告详情页路由注册', function () {
+  var pagesSrc
+
+  beforeAll(function () {
+    pagesSrc = fs.readFileSync(PAGES_JSON_PATH, 'utf8')
+  })
+
+  it('注册 ai-report-detail 路由(跳转目标可达,不白屏)', function () {
+    expect(/"path"\s*:\s*"ai-report-detail"/.test(pagesSrc)).toBe(true)
+  })
+
+  it('报告详情页配置 navigationBarTitleText(页面标题规范)', function () {
+    expect(/ai-report-detail[\s\S]{0,200}navigationBarTitleText/.test(pagesSrc)).toBe(true)
+  })
+})
+
+// ===========================================================================
+// AC-R2 <script> 行为契约:onLoad 按 id 走 aiyunyi.getReport(§4.5 R3 / 附录 A.6)
+// ===========================================================================
+
+describe('AC-R2 报告详情页 <script> 行为契约', function () {
+  var component
+
+  beforeEach(function () {
+    component = loadDetail(DETAIL_PATH).component
+  })
+
+  it('声明报告原始结构 / 加载 / 错误等状态字段', function () {
+    var vm = instantiate(component)
+    expect(vm.reportId).toBeDefined()
+    expect(vm.report).toBeDefined()
+    expect(vm.reportDiseaseRespList).toBeDefined()
+    expect(vm.loading).toBeDefined()
+    expect(vm.errorMessage).toBeDefined()
+  })
+
+  it('onLoad(options) 取报告 id 并调用 aiyunyi.getReport(id),不走 report/page', async function () {
+    getReportSpy.mockResolvedValue({ code: 200, message: 'ok', data: RAW_REPORT })
+    var vm = instantiate(component)
+    expect(typeof vm.onLoad).toBe('function')
+    vm.onLoad({ id: 987 })
+    await flush()
+    expect(getReportSpy).toHaveBeenCalledWith(987)
+    expect(reportPageSpy).not.toHaveBeenCalled()
+  })
+
+  it('报告原始结构 reportDiseaseRespList 写入组件状态(一期按原始结构渲染)', async function () {
+    getReportSpy.mockResolvedValue({ code: 200, message: 'ok', data: RAW_REPORT })
+    var vm = instantiate(component)
+    vm.onLoad({ id: 1 })
+    await flush()
+    expect(vm.reportDiseaseRespList).toEqual(RAW_REPORT.reportDiseaseRespList)
+  })
+
+  it('空数据(data 无报告指标)→ 明确「暂无」提示,不白屏', async function () {
+    getReportSpy.mockResolvedValue({ code: 200, message: 'ok', data: { reportDiseaseRespList: [] } })
+    var vm = instantiate(component)
+    vm.onLoad({ id: 1 })
+    await flush()
+    expect(visibleMessage(vm)).toMatch(/暂无|没有数据|无数据|空/)
+  })
+
+  it('生成中(data.status=GENERATING)→ 明确「生成中」提示', async function () {
+    getReportSpy.mockResolvedValue({
+      code: 200, message: 'ok', data: { status: 'GENERATING', statusText: '报告生成中' }
+    })
+    var vm = instantiate(component)
+    vm.onLoad({ id: 1 })
+    await flush()
+    expect(visibleMessage(vm)).toMatch(/生成中/)
+  })
+
+  it('加载失败(getReport 拒绝)→ 明确「失败/重试」提示,不白屏不崩溃', async function () {
+    getReportSpy.mockRejectedValue(new Error('network error'))
+    var vm = instantiate(component)
+    vm.onLoad({ id: 1 })
+    await flush()
+    expect(visibleMessage(vm)).toMatch(/失败|网络|重试/)
+  })
+
+  it('缺少报告 id(options 无 id)→ 拦截并提示,不发 getReport 请求', async function () {
+    var vm = instantiate(component)
+    vm.onLoad({})
+    await flush()
+    expect(getReportSpy).not.toHaveBeenCalled()
+    expect(visibleMessage(vm)).toMatch(/报告|参数|不存在|无效/)
+  })
+})
+
+// ===========================================================================
+// AC-R3 <template> 结构契约:附录 A.6 原始指标渲染 + 空值规则 + 三分支提示
+// ===========================================================================
+
+describe('AC-R3 报告详情页 <template> 结构契约', function () {
+  var template
+
+  beforeAll(function () {
+    buildModuleStubs()
+    template = loadDetail(DETAIL_PATH).template
+  })
+
+  it('遍历原始结构 reportDiseaseRespList → diseaseDetailList', function () {
+    expect(/reportDiseaseRespList/.test(template)).toBe(true)
+    expect(/diseaseDetailList/.test(template)).toBe(true)
+  })
+
+  it('渲染原始指标字段 diseaseDetailName(Cn) / accuracy / diseaseLevel', function () {
+    expect(/diseaseDetailNameCn|diseaseDetailName/.test(template)).toBe(true)
+    expect(/accuracy/.test(template)).toBe(true)
+    expect(/diseaseLevel/.test(template)).toBe(true)
+  })
+
+  it('附录 A.6 空值规则:diseaseLevel 空 → 「未检出」', function () {
+    expect(/未检出/.test(template)).toBe(true)
+  })
+
+  it('附录 A.6 空值规则:accuracy 空 → 参考值提示(不自行填 0)', function () {
+    expect(/参考/.test(template)).toBe(true)
+  })
+
+  it('空数据分支:模板含「暂无/无数据」提示', function () {
+    expect(/暂无|没有数据|无数据|空/.test(template)).toBe(true)
+  })
+
+  it('生成中分支:模板含「生成中」提示', function () {
+    expect(/生成中/.test(template)).toBe(true)
+  })
+
+  it('加载失败分支:模板含「失败/重试」提示', function () {
+    expect(/加载失败|获取失败|重试|失败/.test(template)).toBe(true)
+  })
+})
+
+// ===========================================================================
+// AC-R4 api.js 静态契约:aiyunyi.getReport 走 /api/aiyunyi/** 后端代理(§3.1/§4.2)
+// ===========================================================================
+
+describe('AC-R4 utils/api.js getReport 封装静态契约', function () {
+  var apiSrc
+
+  beforeAll(function () {
+    apiSrc = fs.readFileSync(API_PATH, 'utf8')
+  })
+
+  /** getReport 声明附近必须绑定 /api/aiyunyi/ 代理前缀 */
+  function getReportBoundToProxy(src) {
+    var re = /getReport/g
+    var match
+    while ((match = re.exec(src)) !== null) {
+      var around = src.slice(Math.max(0, match.index - 400), match.index + 500)
+      if (around.indexOf('/api/aiyunyi/') >= 0) return true
+    }
+    return false
+  }
+
+  it('存在 /api/aiyunyi/** 代理前缀(前端不直连爱云医)', function () {
+    expect(apiSrc.indexOf('/api/aiyunyi/')).toBeGreaterThanOrEqual(0)
+  })
+
+  it('getReport 封装绑定代理前缀(aiyunyi.getReport / aiyunyiGetReport / 平铺)', function () {
+    expect(apiSrc.indexOf('getReport')).toBeGreaterThanOrEqual(0)
+    expect(getReportBoundToProxy(apiSrc)).toBe(true)
+  })
+
+  it('报告详情链路不调用 report/page(R3 缺陷 1011011002 回归锚点)', function () {
+    expect(apiSrc.indexOf('report/page')).toBe(-1)
+  })
+})
+
+// ===========================================================================
+// AC-R5 页面脚本锚点:报告 id 来自 options,不走 report/page(§4.5)
+// ===========================================================================
+
+describe('AC-R5 页面脚本按 id 拉取锚点', function () {
+  var src
+
+  beforeAll(function () {
+    src = readDetailSource()
+  })
+
+  it('onLoad 从 options.id / options.reportId 取报告 id', function () {
+    expect(/options\.(id|reportId)/.test(src)).toBe(true)
+  })
+
+  it('页面脚本不调用 report/page 分页接口(§4.5 R3)', function () {
+    expect(/report\/page/.test(src)).toBe(false)
+  })
+})
+
+// ===========================================================================
+// 权限流:本报告详情页按报告 id 拉取并渲染,无角色门禁分支(不适用项)
+// ===========================================================================
+
+describe.skip('权限流:ai.aiyunyi.reportDetail 无角色门禁,不适用', function () {
+  it('占位:鉴权由统一 Bearer Token 通道承载,详情页仅按 id 渲染(详见汇报)', function () {})
+})