Browse Source

report-types-fe: RED 契约测试 — 删关联商品区测试+新增 guide-list 配置化测试(排序/图标/购买按钮/模板同行)

Agnes Agent 1 day ago
parent
commit
b57d52d932

+ 331 - 0
cfc-frontend/__tests__/specs/report-upload-guide-config.test.js

@@ -0,0 +1,331 @@
+/**
+ * 验收逻辑守卫(TDD-RED):报告上传页「支持的报告类型」配置化改版(后台可配置 guide-list)
+ *
+ * 背景(2026-11-27 报告上传说明区配置化改版,四条用户需求):
+ *   ① 去掉页面最下面的「关联商品」区;
+ *   ② 素质测评/菌群检测等条目里的「商品+购买按钮」缩小、与类型标题放同一行;
+ *   ③ 菌群检测报告、体检报告等所有报告类型一致;
+ *   ④ 该区域改为后台可配置:标题、内容、关联商品都通过后台配置。
+ *   数据源 = utils/api.js 的 getReportTypeLinks()(POST /api/report-parser/types/links),
+ *   返回全部 is_active=1 类型,字段含 typeId/displayName/description/icon/sortOrder/
+ *   linkedProductId/productName,按 sortOrder 升序 + id 升序稳定排序。
+ *
+ * 说明(沿用 cfc-frontend/__tests__/aiyunyi/report-upload.uploadCard.contract.test.js 的
+ *   「加载真实 SFC 源码求值」约定):
+ *   jest 配置为 node 环境、无 vue-jest 挂载组件;本文件直接读取真实 report-upload.vue 的
+ *   <script>/<template> 源码——
+ *     - <script>:把 import 语句替换为注入桩后求值,得到真实组件的
+ *       computed(sortedGuideTypes) 与 methods(guideIcon/guideIconClass) 做行为级断言;
+ *     - <template>:读取模板文本做结构契约断言(guide-title-row 标题与购买按钮同行、
+ *       购买按钮仅在 linkedProductId 时出现、无 linked-products 残留、无 guide-link 残留)。
+ *   同时镜像三个纯决策函数(sortedGuideTypes/guideIcon/hasBuyButton)做边界测试,
+ *   与组件实现逐位对齐(排序兜底/图标回退/按钮可见性)。
+ *   若 GREEN 阶段实现方补齐上述契约,本文件断言即翻绿;当前实现缺失 → 预期 RED。
+ *   本文件不修改 pages/、pages.json、utils/ 任何业务代码。
+ */
+
+import fs from 'fs'
+import path from 'path'
+
+var REPORT_UPLOAD_PATH = path.join(__dirname, '../../pages/health/report-upload.vue')
+
+/** 把 ES import 语句替换为从 globalThis.__reportUploadStubs 取桩的声明(不解析模块,避免污染业务实现) */
+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.__reportUploadStubs[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 加载真实 SFC:返回 { component, template }(component = 真实 <script> 的 export default 对象) */
+function loadReportUpload() {
+  var src = fs.readFileSync(REPORT_UPLOAD_PATH, 'utf8')
+  var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!scriptMatch) throw new Error('无法在 report-upload.vue 中定位 <script> 块')
+  var script = stubImports(scriptMatch[1], globalThis.__reportUploadStubs || {})
+  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()/computed/methods 构造可驱动上下文 */
+function instantiate(component) {
+  var vm = { $set: function (obj, key, val) { obj[key] = val } }
+  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
+}
+
+/** 取真实组件的 computed 定义(未被 instantiate 展开到 vm 上,需单独调用求值) */
+function getComputed(component) {
+  return component.computed || {}
+}
+
+// ---------------------------------------------------------------------------
+// 测试夹具
+// ---------------------------------------------------------------------------
+
+beforeEach(function () {
+  globalThis.__reportUploadStubs = {
+    '../../utils/memberNormalize.js': {
+      normalizeMembers: function (list) { return list || [] },
+      memberIdOf: function (m) { return m && m.id }
+    },
+    '../../utils/api.js': {
+      uploadReportOnly: jest.fn(function () { return Promise.resolve({ data: {} }) }),
+      getReportCollectStatus: jest.fn(function () { return Promise.resolve({ data: {} }) }),
+      getFamilyMemberList: jest.fn(function () { return Promise.resolve({ data: [] }) }),
+      requestReportTransfer: jest.fn(function () { return Promise.resolve({ code: 200 }) }),
+      getReportTypeLinks: jest.fn(function () { return Promise.resolve({ data: [] }) })
+    },
+    '../../utils/image-picker.js': { pickImage: jest.fn() },
+    '@/mixins/font-scale.js': {
+      fontScaleMixin: { data: function () { return { fontScale: 1 } }, onShow: function () {} }
+    }
+  }
+})
+
+afterEach(function () {
+  delete globalThis.__reportUploadStubs
+})
+
+// ---------------------------------------------------------------------------
+// AC1 sortedGuideTypes computed:sortOrder 升序 + typeId 稳定兜底(§配置化改版)
+// ---------------------------------------------------------------------------
+
+describe('AC1 sortedGuideTypes computed', function () {
+  it('组件 computed 中定义 sortedGuideTypes', function () {
+    var component = loadReportUpload().component
+    expect(typeof getComputed(component).sortedGuideTypes).toBe('function')
+  })
+
+  it('sortOrder 升序排列', function () {
+    var component = loadReportUpload().component
+    var vm = instantiate(component)
+    vm.reportTypeLinks = [
+      { typeId: 'dan_a2', sortOrder: 20, displayName: '素质测评' },
+      { typeId: 'gut_flora', sortOrder: 10, displayName: '菌群检测' },
+      { typeId: 'physical_exam', sortOrder: 30, displayName: '体检报告' }
+    ]
+    var out = getComputed(component).sortedGuideTypes.call(vm)
+    expect(out.map(function (x) { return x.typeId })).toEqual(['gut_flora', 'dan_a2', 'physical_exam'])
+  })
+
+  it('sortOrder 空(null/undefined)按 100 兜底排序,相等按 typeId 字符串稳定', function () {
+    var component = loadReportUpload().component
+    var vm = instantiate(component)
+    vm.reportTypeLinks = [
+      { typeId: 'tongue', sortOrder: null, displayName: '舌象照片' },
+      { typeId: 'body_fat', displayName: '体脂秤报告' }, // undefined sortOrder
+      { typeId: 'dan_a2', sortOrder: 10, displayName: '素质测评' }
+    ]
+    var out = getComputed(component).sortedGuideTypes.call(vm)
+    expect(out.map(function (x) { return x.typeId })).toEqual(['dan_a2', 'body_fat', 'tongue'])
+  })
+
+  it('reportTypeLinks 为空/非数组 → 返回 [](不抛错)', function () {
+    var component = loadReportUpload().component
+    var vm = instantiate(component)
+    vm.reportTypeLinks = null
+    expect(getComputed(component).sortedGuideTypes.call(vm)).toEqual([])
+    vm.reportTypeLinks = 'not-array'
+    expect(getComputed(component).sortedGuideTypes.call(vm)).toEqual([])
+  })
+
+  it('不修改原数组(深比较)', function () {
+    var component = loadReportUpload().component
+    var vm = instantiate(component)
+    vm.reportTypeLinks = [
+      { typeId: 'dan_a2', sortOrder: 20 },
+      { typeId: 'gut_flora', sortOrder: 10 }
+    ]
+    var before = JSON.stringify(vm.reportTypeLinks)
+    getComputed(component).sortedGuideTypes.call(vm)
+    expect(JSON.stringify(vm.reportTypeLinks)).toBe(before)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC2 guideIcon(item):icon 优先,空回退 typeId 映射,未知回退 📄
+// ---------------------------------------------------------------------------
+
+describe('AC2 guideIcon(item) 图标回退', function () {
+  it('组件 methods 中定义 guideIcon', function () {
+    var component = loadReportUpload().component
+    expect(typeof instantiate(component).guideIcon).toBe('function')
+  })
+
+  it('有 icon 字段 → 优先使用', function () {
+    var vm = instantiate(loadReportUpload().component)
+    expect(vm.guideIcon({ typeId: 'gut_flora', icon: '🦠' })).toBe('🦠')
+    expect(vm.guideIcon({ typeId: 'unknown_xyz', icon: '🌟' })).toBe('🌟')
+  })
+
+  it('icon 为空 → 回退 typeId 默认映射(gut_flora/dan_a2/physical_exam/tongue/body_fat)', function () {
+    var vm = instantiate(loadReportUpload().component)
+    expect(vm.guideIcon({ typeId: 'gut_flora' })).toBe('📄')
+    expect(vm.guideIcon({ typeId: 'dan_a2', icon: '' })).toBe('🧠')
+    expect(vm.guideIcon({ typeId: 'physical_exam', icon: null })).toBe('📋')
+    expect(vm.guideIcon({ typeId: 'tongue' })).toBe('👅')
+    expect(vm.guideIcon({ typeId: 'body_fat' })).toBe('⚖️')
+  })
+
+  it('未知 typeId / 无 typeId / item 为 null → 回退 📄', function () {
+    var vm = instantiate(loadReportUpload().component)
+    expect(vm.guideIcon({ typeId: 'some_new_type' })).toBe('📄')
+    expect(vm.guideIcon({})).toBe('📄')
+    expect(vm.guideIcon(null)).toBe('📄')
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC3 guideIconClass(idx):循环四色视觉(blue/purple/orange/teal 按位取模)
+// ---------------------------------------------------------------------------
+
+describe('AC3 guideIconClass(idx) 循环四色', function () {
+  it('组件 methods 中定义 guideIconClass', function () {
+    var component = loadReportUpload().component
+    expect(typeof instantiate(component).guideIconClass).toBe('function')
+  })
+
+  it('按 idx 取模返回四色 class', function () {
+    var vm = instantiate(loadReportUpload().component)
+    expect(vm.guideIconClass(0)).toBe('guide-icon-blue')
+    expect(vm.guideIconClass(1)).toBe('guide-icon-purple')
+    expect(vm.guideIconClass(2)).toBe('guide-icon-orange')
+    expect(vm.guideIconClass(3)).toBe('guide-icon-teal')
+    expect(vm.guideIconClass(4)).toBe('guide-icon-blue') // 循环
+  })
+})
+
+// ---------------------------------------------------------------------------
+// AC4 模板结构契约:标题与购买按钮同行、购买按钮仅在 linkedProductId 时出现、
+//     无 linked-products 残留、无 guide-link 残留(§配置化改版 ①②③)
+// ---------------------------------------------------------------------------
+
+describe('AC4 模板结构契约', function () {
+  var template
+  beforeAll(function () {
+    globalThis.__reportUploadStubs = {}
+    template = loadReportUpload().template
+  })
+
+  it('guide-item 为 v-for 配置驱动(含 sortedGuideTypes 数据源,§④后台可配置)', function () {
+    expect(template).toMatch(/v-for="[^"]*\bsortedGuideTypes\b/)
+  })
+
+  it('标题与购买按钮同一行:guide-title-row 内含 guide-name 与 guide-buy(§②同行)', function () {
+    var start = template.indexOf('guide-title-row')
+    expect(start).toBeGreaterThan(-1)
+    var rowStart = template.lastIndexOf('<view class="guide-title-row"', start)
+    expect(rowStart).toBeGreaterThan(-1)
+    var rowEnd = template.indexOf('</view>', start)
+    var block = template.slice(rowStart, rowEnd)
+    expect(block).toMatch(/class="guide-name"/)
+    expect(block).toMatch(/class="guide-buy"/)
+  })
+
+  it('购买按钮仅在 linkedProductId 时出现(v-if="item.linkedProductId",§②缩小+一致)', function () {
+    expect(template).toMatch(/class="guide-buy"[^>]*v-if="item\.linkedProductId"|v-if="item\.linkedProductId"[^>]*class="guide-buy"/)
+  })
+
+  it('已删除重复的 guide-link(查看商品)块(§②去重复,只留一个小购买按钮)', function () {
+    expect(template).not.toMatch(/class="guide-link"/)
+  })
+
+  it('已删除「关联商品」区(linked-products-section,§①去掉底部关联商品区)', function () {
+    expect(template).not.toMatch(/linked-products-section/)
+    expect(template).not.toMatch(/linked-product-card/)
+  })
+})
+
+// ---------------------------------------------------------------------------
+// 镜像纯决策函数(边界守卫,与组件实现逐位对齐)
+// ---------------------------------------------------------------------------
+
+function sortedGuideTypesMirror(links) {
+  if (!Array.isArray(links)) return []
+  return links.slice().sort(function (a, b) {
+    var sa = (a && a.sortOrder !== null && a.sortOrder !== undefined) ? a.sortOrder : 100
+    var sb = (b && b.sortOrder !== null && b.sortOrder !== undefined) ? b.sortOrder : 100
+    if (sa !== sb) return sa - sb
+    var ta = String((a && a.typeId) || '')
+    var tb = String((b && b.typeId) || '')
+    return ta < tb ? -1 : (ta > tb ? 1 : 0)
+  })
+}
+
+function hasBuyButtonMirror(item) {
+  if (!item) return false
+  var pid = item.linkedProductId
+  if (pid === null || pid === undefined || pid === '') return false
+  if (pid === 0) return false
+  return true
+}
+
+describe('镜像守卫 sortedGuideTypesMirror', function () {
+  it('非数组/空 → []', function () {
+    expect(sortedGuideTypesMirror(null)).toEqual([])
+    expect(sortedGuideTypesMirror(undefined)).toEqual([])
+    expect(sortedGuideTypesMirror('not-array')).toEqual([])
+    expect(sortedGuideTypesMirror([])).toEqual([])
+  })
+
+  it('sortOrder 升序;空按 100 兜底;相等按 typeId 稳定', function () {
+    var links = [
+      { typeId: 'tongue', sortOrder: null },
+      { typeId: 'body_fat' },
+      { typeId: 'dan_a2', sortOrder: 10 }
+    ]
+    expect(sortedGuideTypesMirror(links).map(function (x) { return x.typeId })).toEqual(['dan_a2', 'body_fat', 'tongue'])
+  })
+
+  it('不修改原数组', function () {
+    var links = [{ typeId: 'dan_a2', sortOrder: 20 }, { typeId: 'gut_flora', sortOrder: 10 }]
+    var before = JSON.stringify(links)
+    sortedGuideTypesMirror(links)
+    expect(JSON.stringify(links)).toBe(before)
+  })
+})
+
+describe('镜像守卫 hasBuyButtonMirror', function () {
+  it('linkedProductId 非空(正数/字符串数字) → true', function () {
+    expect(hasBuyButtonMirror({ linkedProductId: 100 })).toBe(true)
+    expect(hasBuyButtonMirror({ linkedProductId: '200' })).toBe(true)
+  })
+
+  it('linkedProductId = 0 / null / undefined / 空串 → false;item null → false', function () {
+    expect(hasBuyButtonMirror({ linkedProductId: 0 })).toBe(false)
+    expect(hasBuyButtonMirror({ linkedProductId: null })).toBe(false)
+    expect(hasBuyButtonMirror({})).toBe(false)
+    expect(hasBuyButtonMirror({ linkedProductId: '' })).toBe(false)
+    expect(hasBuyButtonMirror(null)).toBe(false)
+  })
+})

+ 0 - 84
cfc-frontend/__tests__/specs/report-upload-linked-products.test.js

@@ -1,84 +0,0 @@
-/**
- * 验收逻辑守卫:报告上传页「关联商品」卡片区按商品 id 去重
- * 对应需求文档:docs/需求分析/2026-11-06-报告上传页关联商品卡片需求变更.md(变更 R1)
- * 实现任务书:docs/superpowers/specs/2026-11-06-report-upload-product-cards.md(已合入 cfclub 0bdc78def)
- *
- * 说明(与仓库既有约定一致,见 coupon-claimed-actions.test.js):
- *   cfc-frontend jest 配置 testEnvironment=node,无 vue-jest,.vue SFC 方法无法直接挂载。
- *   约定是把组件中「纯决策逻辑」抽取为本地函数在此测试。以下函数镜像
- *   report-upload.vue 的 `linkedProducts` computed(spec §变更 R1):
- *     遍历 reportTypeLinks,用 Set 按商品 id(linkedProductId) 去重
- *     (parseInt 后过滤 null/0/NaN),返回 [{productId, productName}];
- *     同商品多个报告类型只保留一条(productName 取首个匹配);接口失败/未配置返回 []。
- *
- *   建议(非本闭环范围,禁止改生产源码):将 dedupLinkedProducts 抽到
- *   utils/reportUpload.js,届时本测试直接 import 真实实现即可升级为真正单测。
- */
-
-// ---- 镜像 report-upload.vue linkedProducts computed 的去重逻辑 ----
-function dedupLinkedProducts(links) {
-  if (!Array.isArray(links)) return []
-  const seen = new Set()
-  const out = []
-  for (const link of links) {
-    if (!link || !link.linkedProductId) continue
-    const pid = parseInt(link.linkedProductId, 10)
-    if (!pid || Number.isNaN(pid)) continue // 过滤 null/0/NaN
-    if (seen.has(pid)) continue // 同商品多个报告类型只保留一条
-    seen.add(pid)
-    out.push({ productId: pid, productName: link.productName })
-  }
-  return out
-}
-
-describe('dedupLinkedProducts - 关联商品按商品id去重', () => {
-  it('接口失败/未配置(非数组) → 返回 []', () => {
-    expect(dedupLinkedProducts(null)).toEqual([])
-    expect(dedupLinkedProducts(undefined)).toEqual([])
-    expect(dedupLinkedProducts('not-array')).toEqual([])
-  })
-
-  it('空数组(未配置任何关联商品) → 返回 [](静默隐藏)', () => {
-    expect(dedupLinkedProducts([])).toEqual([])
-  })
-
-  it('两个报告类型挂同一商品 → 只保留一条(productName 取首个匹配)', () => {
-    const links = [
-      { typeId: 1, linkedProductId: 100, productName: '益生菌' },
-      { typeId: 2, linkedProductId: 100, productName: '益生菌(重复)' }
-    ]
-    expect(dedupLinkedProducts(links)).toEqual([{ productId: 100, productName: '益生菌' }])
-  })
-
-  it('linkedProductId 为字符串数字 → parseInt 后正确去重', () => {
-    const links = [
-      { typeId: 1, linkedProductId: '200', productName: 'A' },
-      { typeId: 2, linkedProductId: 200, productName: 'B' }
-    ]
-    // '200' 与 200 视为同一商品 → 只保留一条
-    expect(dedupLinkedProducts(links)).toEqual([{ productId: 200, productName: 'A' }])
-  })
-
-  it('过滤无效 linkedProductId(null/0/NaN)', () => {
-    const links = [
-      { typeId: 1, linkedProductId: null, productName: 'X' },
-      { typeId: 2, linkedProductId: 0, productName: 'Y' },
-      { typeId: 3, linkedProductId: 'abc', productName: 'Z' },
-      { typeId: 4, linkedProductId: 300, productName: '有效' }
-    ]
-    expect(dedupLinkedProducts(links)).toEqual([{ productId: 300, productName: '有效' }])
-  })
-
-  it('不同商品 → 多条互不干扰', () => {
-    const links = [
-      { typeId: 1, linkedProductId: 100, productName: 'A' },
-      { typeId: 2, linkedProductId: 200, productName: 'B' },
-      { typeId: 3, linkedProductId: 300, productName: 'C' }
-    ]
-    expect(dedupLinkedProducts(links)).toEqual([
-      { productId: 100, productName: 'A' },
-      { productId: 200, productName: 'B' },
-      { productId: 300, productName: 'C' }
-    ])
-  })
-})