articleSearch.contract.test.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. /**
  2. * 契约级单测(TDD-RED→GREEN)——能力键 content.article.search(前端部分 C4-C6)
  3. *
  4. * 溯源:
  5. * requirement: docs/需求分析/2026-11-14-小程序知识分享页搜索功能需求变更.md
  6. * (ARTICLE-SEARCH-2026-11-14-V1,契约 C4 触发语义 / C5 空态区分 / C6 标签互斥重置)
  7. * design: docs/design/2026-11-14-article-center-search-design.md
  8. * (D3 前端交互完善 + D3a 输入防抖与搜索历史,交互参考 pages/shop/search/search.vue)
  9. * 契约布局:___tests__/api/api.test.js(C4 请求体 keyword 透传断言)+ 本文件(页面方法/空态/互斥)
  10. *
  11. * 说明(既有 Jest 体系约束):
  12. * cfc-frontend 无 vue-jest/jsdom 组件环境 —— 沿用「读取真实 SFC 源码 → 桩化 import → 求值
  13. * <script> 拿真实 export default → 驱动 data()/methods/computed 做行为断言,模板做结构断言」,
  14. * 参考 __tests__/pages/article-center/articleTagFilter.contract.test.js。
  15. * 本文件不修改 pages/、utils/ 任何业务代码。
  16. *
  17. * 小程序约束(AGENTS.md):禁可选链 ?.、禁 CSS Grid、禁 :key 表达式、禁 new Date(string)。
  18. */
  19. import fs from 'fs'
  20. import path from 'path'
  21. import { BrandColors } from '@/utils/brand-colors.js'
  22. const PAGE_PATH = path.join(__dirname, '../../../pages/article-center/index.vue')
  23. /** 把 ES import 语句替换为从 globalThis.__articleCenterSearchStubs 取桩的声明(不解析模块,避免污染业务实现) */
  24. function stubImports(script, stubMap) {
  25. return script.replace(/import\s+([^;]+?)\s+from\s+['"]([^'"]+)['"];?/g, function (m, clause, id) {
  26. var names = []
  27. var c = clause.trim()
  28. var braceIdx = c.indexOf('{')
  29. if (braceIdx >= 0) {
  30. var def = c.slice(0, braceIdx).replace(/,\s*$/, '').trim()
  31. if (def) names.push(def)
  32. var named = c.slice(braceIdx + 1, c.lastIndexOf('}'))
  33. named.split(',').forEach(function (part) {
  34. var p = part.trim()
  35. if (!p) return
  36. var parts = p.split(/\s+as\s+/)
  37. var local = parts.length > 1 ? parts[1].trim() : parts[0].trim()
  38. if (local) names.push(local)
  39. })
  40. } else if (c.indexOf('*') === 0) {
  41. var nsMatch = c.match(/\*\s+as\s+(\w+)/)
  42. if (nsMatch) names.push(nsMatch[1])
  43. } else {
  44. names.push(c)
  45. }
  46. return names.map(function (n) {
  47. return 'var ' + n + ' = ((globalThis.__articleCenterSearchStubs || {})[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
  48. }).join('\n')
  49. })
  50. }
  51. /** 加载真实 SFC:返回 { component, template }(component = 真实 <script> 的 export default 对象) */
  52. function loadPage() {
  53. var src = fs.readFileSync(PAGE_PATH, 'utf8')
  54. var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
  55. var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
  56. if (!scriptMatch) throw new Error('无法在 article-center/index.vue 中定位 <script> 块')
  57. var script = stubImports(scriptMatch[1], globalThis.__articleCenterSearchStubs || {})
  58. script = script.replace(/export default\s*\{/, 'module.exports = {')
  59. var mod = { exports: {} }
  60. // eslint-disable-next-line no-new-func
  61. var fn = new Function('module', 'exports', script)
  62. fn(mod, mod.exports)
  63. return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '' }
  64. }
  65. /** 依据真实组件的 data()/methods/computed 构造可驱动上下文(模拟 Vue 合并实例) */
  66. function instantiate(component) {
  67. var vm = {}
  68. var data = typeof component.data === 'function' ? component.data.call(vm) : (component.data || {})
  69. Object.keys(data).forEach(function (k) { vm[k] = data[k] })
  70. var methods = component.methods || {}
  71. Object.keys(methods).forEach(function (k) { vm[k] = methods[k] })
  72. var computed = component.computed || {}
  73. Object.keys(computed).forEach(function (k) {
  74. Object.defineProperty(vm, k, { get: computed[k], enumerable: true, configurable: true })
  75. })
  76. return vm
  77. }
  78. /** 每次调用时重新加载真实 SFC(读取当时的 __articleCenterSearchStubs),避免闭包捕获旧桩 */
  79. function getComponent() {
  80. return loadPage().component
  81. }
  82. /** 刷新微任务队列:让 fire-and-forget 的 async 方法(loadArticles 等)结算完成 */
  83. function flushPromises() {
  84. return new Promise(function (resolve) { setTimeout(resolve, 0) })
  85. }
  86. // ---------------------------------------------------------------------------
  87. // 测试夹具
  88. // ---------------------------------------------------------------------------
  89. var stubs
  90. beforeEach(function () {
  91. global.uni._storage = {}
  92. global.uni.showToast.mockReset()
  93. global.uni.navigateTo.mockReset()
  94. global.uni.request.mockReset()
  95. stubs = {
  96. getArticleList: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: { records: [], total: 0 } }) }),
  97. getArticleTags: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) }),
  98. getFeaturedArticles: jest.fn(function () { return Promise.resolve({ code: 200, message: 'ok', data: [] }) })
  99. }
  100. globalThis.__articleCenterSearchStubs = {
  101. '../../utils/brand-colors.js': { BrandColors: BrandColors },
  102. '@/utils/api.js': {
  103. getArticleList: stubs.getArticleList,
  104. getArticleTags: stubs.getArticleTags,
  105. getFeaturedArticles: stubs.getFeaturedArticles
  106. },
  107. '@/config.js': { config: { API_BASE_URL: 'http://127.0.0.1:9082' } },
  108. '@/mixins/font-scale.js': { fontScaleMixin: { data: function () { return {} } } }
  109. }
  110. })
  111. afterEach(function () {
  112. delete globalThis.__articleCenterSearchStubs
  113. })
  114. // ---------------------------------------------------------------------------
  115. // 契约 C4:触发语义 —— onSearch 重置分页/清列表/noMore=false,请求体携带 trim keyword;
  116. // 空 keyword(取消)还原全量;400ms 防抖即时搜索;搜索历史本地存储(上限 10、去重、可清空)
  117. // ---------------------------------------------------------------------------
  118. describe('契约C4 index.vue:onSearch 触发语义 + 防抖 + 搜索历史', function () {
  119. test('onSearch 同步重置 page=1/articles=[]/noMore=false,请求体携带 trim 后的 keyword', async function () {
  120. stubs.getArticleList.mockResolvedValue({ code: 200, message: 'ok', data: { records: [{ id: 1, title: '睡眠指南' }], total: 1 } })
  121. var vm = instantiate(getComponent())
  122. vm.currentChildId = null
  123. vm.page = 5
  124. vm.articles = [{ id: 999 }]
  125. vm.noMore = true
  126. vm.searchKeyword = ' 睡眠 '
  127. vm.onSearch()
  128. // 提交瞬间即重置(契约 C4:page=1、列表清空、noMore=false)
  129. expect(vm.page).toBe(1)
  130. expect(vm.articles).toEqual([])
  131. expect(vm.noMore).toBe(false)
  132. await flushPromises()
  133. var params = stubs.getArticleList.mock.calls[0][0]
  134. expect(params.keyword).toBe('睡眠')
  135. expect(vm.articles).toEqual([{ id: 1, title: '睡眠指南' }])
  136. })
  137. test('onSearch 空 keyword(取消语义)→ 还原全量,请求体不带 keyword 且历史不落盘', async function () {
  138. stubs.getArticleList.mockResolvedValue({ code: 200, message: 'ok', data: { records: [{ id: 2, title: 'x' }], total: 1 } })
  139. var vm = instantiate(getComponent())
  140. vm.currentChildId = null
  141. vm.searchKeyword = ' '
  142. vm.onSearch()
  143. await flushPromises()
  144. var params = stubs.getArticleList.mock.calls[0][0]
  145. expect(params.keyword).toBeUndefined()
  146. expect(params.tag).toBeUndefined()
  147. expect(vm.articles).toEqual([{ id: 2, title: 'x' }])
  148. expect(global.uni._storage['article_search_history']).toBeUndefined()
  149. })
  150. test('模板:搜索框保留 v-model/@confirm 并接入 @input="onSearchInput" 防抖', function () {
  151. var template = loadPage().template
  152. expect(template).toMatch(/v-model="searchKeyword"/)
  153. expect(template).toMatch(/@confirm="onSearch"/)
  154. expect(template).toMatch(/@input="onSearchInput"/)
  155. })
  156. test('onSearchInput 400ms 防抖即时搜索:只发一次且携带当前 keyword', function () {
  157. jest.useFakeTimers()
  158. try {
  159. stubs.getArticleList.mockResolvedValue({ code: 200, message: 'ok', data: { records: [], total: 0 } })
  160. var vm = instantiate(getComponent())
  161. vm.currentChildId = null
  162. vm.searchKeyword = '睡眠'
  163. vm.onSearchInput({ detail: { value: '睡眠' } })
  164. expect(stubs.getArticleList).not.toHaveBeenCalled()
  165. jest.advanceTimersByTime(399)
  166. expect(stubs.getArticleList).not.toHaveBeenCalled()
  167. jest.advanceTimersByTime(1)
  168. expect(stubs.getArticleList).toHaveBeenCalledTimes(1)
  169. expect(stubs.getArticleList.mock.calls[0][0].keyword).toBe('睡眠')
  170. } finally {
  171. jest.useRealTimers()
  172. }
  173. })
  174. test('onSearchInput 连续输入只在防抖窗口结束后请求一次并取最新词', function () {
  175. jest.useFakeTimers()
  176. try {
  177. var vm = instantiate(getComponent())
  178. vm.currentChildId = null
  179. vm.onSearchInput({ detail: { value: '睡' } })
  180. vm.onSearchInput({ detail: { value: '睡眠' } })
  181. vm.onSearchInput({ detail: { value: ' 睡眠法 ' } })
  182. expect(stubs.getArticleList).not.toHaveBeenCalled()
  183. jest.advanceTimersByTime(400)
  184. expect(stubs.getArticleList).toHaveBeenCalledTimes(1)
  185. expect(stubs.getArticleList.mock.calls[0][0].keyword).toBe('睡眠法')
  186. } finally {
  187. jest.useRealTimers()
  188. }
  189. })
  190. test('onSearch 保存 trim 关键词到本地历史(article_search_history):去重、提到最前', function () {
  191. var vm = instantiate(getComponent())
  192. vm.searchKeyword = '睡眠'
  193. vm.onSearch()
  194. expect(vm.searchHistory).toEqual(['睡眠'])
  195. expect(JSON.parse(global.uni._storage['article_search_history'])).toEqual(['睡眠'])
  196. vm.searchKeyword = '成长'
  197. vm.onSearch()
  198. expect(vm.searchHistory).toEqual(['成长', '睡眠'])
  199. // 去重:再次搜索相同关键词提到最前
  200. vm.searchKeyword = '睡眠'
  201. vm.onSearch()
  202. expect(vm.searchHistory).toEqual(['睡眠', '成长'])
  203. expect(vm.searchHistory.length).toBe(2)
  204. })
  205. test('搜索历史上限 10 条,超出丢弃最旧', function () {
  206. var vm = instantiate(getComponent())
  207. var seed = []
  208. for (var i = 1; i <= 10; i++) seed.push('k' + i)
  209. vm.searchHistory = seed.slice()
  210. vm.searchKeyword = 'new'
  211. vm.onSearch()
  212. expect(vm.searchHistory.length).toBe(10)
  213. expect(vm.searchHistory[0]).toBe('new')
  214. expect(vm.searchHistory[9]).toBe('k9')
  215. expect(vm.searchHistory.indexOf('k10')).toBe(-1)
  216. })
  217. test('onLoad 读取历史;非法 JSON 容错为空数组', async function () {
  218. global.uni._storage['article_search_history'] = JSON.stringify(['睡眠', '成长'])
  219. var vm = instantiate(getComponent())
  220. var opts = getComponent()
  221. await opts.onLoad.call(vm, {})
  222. await flushPromises()
  223. expect(vm.searchHistory).toEqual(['睡眠', '成长'])
  224. global.uni._storage['article_search_history'] = '{bad json'
  225. var vm2 = instantiate(getComponent())
  226. await opts.onLoad.call(vm2, {})
  227. expect(vm2.searchHistory).toEqual([])
  228. })
  229. test('clearSearchHistory 清空列表并删除本地存储', function () {
  230. var vm = instantiate(getComponent())
  231. vm.searchHistory = ['睡眠']
  232. global.uni._storage['article_search_history'] = JSON.stringify(['睡眠'])
  233. vm.clearSearchHistory()
  234. expect(vm.searchHistory).toEqual([])
  235. expect(global.uni._storage['article_search_history']).toBeUndefined()
  236. })
  237. test('模板:搜索历史条 v-for 渲染 searchHistory,点击历史项回填关键词', function () {
  238. var template = loadPage().template
  239. expect(template).toMatch(/v-for="\(item, idx\) in searchHistory"/)
  240. expect(template).toMatch(/searchHistory.length/)
  241. expect(template).toMatch(/clickSearchHistory\(item\)/)
  242. expect(template).toMatch(/clearSearchHistory/)
  243. })
  244. })
  245. // ---------------------------------------------------------------------------
  246. // 契约 C5:空态区分 —— noMore && articles.length === 0 时,
  247. // searchKeyword 非空 →「未找到相关文章」,否则 →「暂无文章」
  248. // ---------------------------------------------------------------------------
  249. describe('契约C5 index.vue:搜索空态与「暂无文章」区分', function () {
  250. test('模板:空态门禁 noMore && articles.length === 0,文案按 isSearchEmpty 区分', function () {
  251. var template = loadPage().template
  252. expect(template).toMatch(/v-else-if="noMore && articles\.length === 0"/)
  253. expect(template).toMatch(/未找到相关文章/)
  254. expect(template).toMatch(/暂无文章/)
  255. expect(template).toMatch(/isSearchEmpty/)
  256. })
  257. test('搜索无命中(records=[] total=0)→ articles=[] 且 noMore=true,isSearchEmpty=true', async function () {
  258. stubs.getArticleList.mockResolvedValue({ code: 200, message: 'ok', data: { records: [], total: 0 } })
  259. var vm = instantiate(getComponent())
  260. vm.currentChildId = null
  261. vm.searchKeyword = '睡眠'
  262. vm.onSearch()
  263. await flushPromises()
  264. expect(vm.articles).toEqual([])
  265. expect(vm.noMore).toBe(true)
  266. expect(vm.isSearchEmpty).toBe(true)
  267. })
  268. test('非搜索态空列表(无 keyword)→ isSearchEmpty=false(走「暂无文章」)', async function () {
  269. stubs.getArticleList.mockResolvedValue({ code: 200, message: 'ok', data: { records: [], total: 0 } })
  270. var vm = instantiate(getComponent())
  271. vm.currentChildId = null
  272. vm.searchKeyword = ''
  273. vm.onSearch()
  274. await flushPromises()
  275. expect(vm.articles).toEqual([])
  276. expect(vm.noMore).toBe(true)
  277. expect(vm.isSearchEmpty).toBe(false)
  278. })
  279. })
  280. // ---------------------------------------------------------------------------
  281. // 契约 C6:互斥重置 —— 进入搜索态清当前 Tab 回全量;切换 Tab 清搜索关键词与焦点
  282. // ---------------------------------------------------------------------------
  283. describe('契约C6 index.vue:搜索与标签筛选互斥重置', function () {
  284. test('onTabChange 清空 searchKeyword/searchFocused,请求体带 tag 且不带 keyword', async function () {
  285. var vm = instantiate(getComponent())
  286. vm.currentChildId = null
  287. vm.searchKeyword = '睡眠'
  288. vm.searchFocused = true
  289. vm.onTabChange('减脂')
  290. expect(vm.currentTab).toBe('减脂')
  291. expect(vm.searchKeyword).toBe('')
  292. expect(vm.searchFocused).toBe(false)
  293. await flushPromises()
  294. var params = stubs.getArticleList.mock.calls[0][0]
  295. expect(params.tag).toBe('减脂')
  296. expect(params.keyword).toBeUndefined()
  297. })
  298. test('focusSearch 进入搜索态:清当前 Tab 回全量并重拉全量列表(无 tag)', async function () {
  299. var vm = instantiate(getComponent())
  300. vm.currentChildId = null
  301. vm.currentTab = '减脂'
  302. vm.focusSearch()
  303. expect(vm.searchFocused).toBe(true)
  304. expect(vm.currentTab).toBe('')
  305. expect(vm.page).toBe(1)
  306. expect(vm.articles).toEqual([])
  307. await flushPromises()
  308. var params = stubs.getArticleList.mock.calls[0][0]
  309. expect(params.tag).toBeUndefined()
  310. })
  311. test('focusSearch 已在全量时不重复重拉列表', function () {
  312. var vm = instantiate(getComponent())
  313. vm.currentChildId = null
  314. vm.currentTab = ''
  315. stubs.getArticleList.mockClear()
  316. vm.focusSearch()
  317. expect(vm.searchFocused).toBe(true)
  318. expect(vm.currentTab).toBe('')
  319. expect(stubs.getArticleList).not.toHaveBeenCalled()
  320. })
  321. test('标签态发起搜索(onSearch)→ currentTab 清空回全量,请求体无 tag 只带 keyword', async function () {
  322. stubs.getArticleList.mockResolvedValue({ code: 200, message: 'ok', data: { records: [{ id: 7, title: '睡眠' }], total: 1 } })
  323. var vm = instantiate(getComponent())
  324. vm.currentChildId = null
  325. vm.currentTab = '减脂'
  326. vm.searchKeyword = '睡眠'
  327. vm.onSearch()
  328. expect(vm.currentTab).toBe('')
  329. await flushPromises()
  330. var params = stubs.getArticleList.mock.calls[0][0]
  331. expect(params.keyword).toBe('睡眠')
  332. expect(params.tag).toBeUndefined()
  333. })
  334. })