mobile-quote-versions-lifecycle.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. import assert from 'node:assert/strict'
  2. import test from 'node:test'
  3. import { readFileSync } from 'node:fs'
  4. import { parse } from '@vue/compiler-sfc'
  5. import ts from 'typescript'
  6. import * as vue from 'vue'
  7. import { formatQuoteMoney, getMpQuoteAmountSummary } from '../src/utils/mp-crm-quote-card'
  8. const descriptor = parse(
  9. readFileSync(new URL('../src/views/m/crm/quote/versions.vue', import.meta.url), 'utf8')
  10. ).descriptor
  11. const ast = ts.createSourceFile(
  12. 'versions.ts',
  13. descriptor.scriptSetup!.content,
  14. ts.ScriptTarget.Latest,
  15. true
  16. )
  17. const statements = ast.statements.filter((s) => !ts.isImportDeclaration(s))
  18. const names = statements.flatMap((s) =>
  19. ts.isFunctionDeclaration(s)
  20. ? [s.name!.text]
  21. : ts.isVariableStatement(s)
  22. ? s.declarationList.declarations.map((d) => d.name.getText(ast))
  23. : []
  24. )
  25. const code = ts.transpile(statements.map((s) => s.getText(ast)).join('\n'), {
  26. target: ts.ScriptTarget.ESNext
  27. })
  28. function deferred() {
  29. let resolve!: (value: any) => void
  30. let reject!: (error: Error) => void
  31. const promise = new Promise<any>((yes, no) => {
  32. resolve = yes
  33. reject = no
  34. })
  35. return { promise, resolve, reject }
  36. }
  37. const flush = async () => {
  38. for (let i = 0; i < 12; i++) await Promise.resolve()
  39. }
  40. const destination = (id = 'A', name = 'MpCrmQuoteVersions', query = {}) => ({
  41. name,
  42. params: { id },
  43. query
  44. })
  45. // Execute the entire real SFC setup in a mounted Vue component: lifecycle and watchers are real.
  46. function mount(initial = destination()) {
  47. const current = vue.shallowRef(initial)
  48. const route = Object.fromEntries(['name', 'params', 'query'].map((key) => [key, null]))
  49. for (const key of Object.keys(route))
  50. Object.defineProperty(route, key, { get: () => current.value[key] })
  51. const reads: any[] = [],
  52. navigation: any[] = []
  53. const transport = (kind: string) => (value: string) => {
  54. const d = deferred()
  55. reads.push({ kind, value, ...d })
  56. return d.promise
  57. }
  58. let api: any
  59. const bindings = {
  60. ...Object.fromEntries(
  61. Object.entries(vue).filter(([k]) => /^[a-zA-Z_$][\w$]*$/.test(k) && k !== 'default')
  62. ),
  63. useRoute: () => route,
  64. useRouter: () => ({
  65. push: (v: any) => navigation.push(v),
  66. back: () => navigation.push('back')
  67. }),
  68. useDictStore: () => ({ getLabel: (_: string, v: string) => v, getTagType: () => 'info' }),
  69. getQuote: transport('detail'),
  70. queryVersions: transport('versions'),
  71. formatQuoteMoney,
  72. getMpQuoteAmountSummary
  73. }
  74. const renderer = vue.createRenderer<any, any>({
  75. patchProp() {},
  76. insert() {},
  77. remove() {},
  78. createElement: () => ({}),
  79. createText: () => ({}),
  80. createComment: () => ({}),
  81. setText() {},
  82. setElementText() {},
  83. parentNode: () => null,
  84. nextSibling: () => null
  85. })
  86. const app = renderer.createApp({
  87. setup() {
  88. api = new Function(...Object.keys(bindings), `${code};return {${names.join(',')}}`)(
  89. ...Object.values(bindings)
  90. )
  91. return () => vue.h('div')
  92. }
  93. })
  94. app.mount({})
  95. return {
  96. api,
  97. reads,
  98. navigation,
  99. go: (v: any) => {
  100. current.value = v
  101. },
  102. unmount: () => app.unmount()
  103. }
  104. }
  105. async function detail(h: ReturnType<typeof mount>, index = h.reads.length - 1) {
  106. h.reads[index].resolve({
  107. data: { id: h.reads[index].value, quoteNo: `Q-${h.reads[index].value}` }
  108. })
  109. await flush()
  110. }
  111. async function rows(h: ReturnType<typeof mount>, value: any[] = [{ id: 'version-A' }]) {
  112. h.reads.at(-1).resolve({ data: value })
  113. await flush()
  114. }
  115. test('auth gate, ready idempotence and same-ID query changes', async () => {
  116. const h = mount()
  117. void h.api.loadVersions()
  118. h.go(destination('B'))
  119. assert.equal(h.reads.length, 0)
  120. h.api.onShellReady()
  121. h.api.onShellReady()
  122. assert.equal(h.reads.length, 1)
  123. h.go(destination('B', 'MpCrmQuoteVersions', { tab: 'new' }))
  124. assert.equal(h.reads.length, 1)
  125. await detail(h)
  126. await rows(h)
  127. h.api.onShellReady()
  128. assert.equal(h.reads.length, 2)
  129. h.unmount()
  130. })
  131. for (const aba of [false, true])
  132. for (const stage of ['detail', 'versions'])
  133. for (const reject of [false, true]) {
  134. test(`latest route owns both awaits: ABA=${aba}, stage=${stage}, reject=${reject}`, async () => {
  135. const h = mount()
  136. h.api.onShellReady()
  137. if (stage === 'versions') await detail(h)
  138. const old = h.reads.at(-1)
  139. h.go(destination('B'))
  140. if (aba) h.go(destination('A'))
  141. assert.equal(h.reads.at(-1).value, aba ? 'A' : 'B')
  142. assert.deepEqual(h.api.versions.value, [])
  143. const count = h.reads.length
  144. if (reject) old.reject(new Error('stale failure'))
  145. else old.resolve(stage === 'detail' ? { id: 'A', quoteNo: 'old' } : [{ id: 'old' }])
  146. await flush()
  147. assert.equal(h.reads.length, count, 'old detail cannot issue second read')
  148. assert.equal(h.api.loading.value, true, 'old finally cannot end new loading')
  149. assert.equal(h.api.errorText.value, '')
  150. assert.deepEqual(h.api.versions.value, [])
  151. await detail(h)
  152. await rows(h, [{ id: 'fresh' }])
  153. assert.equal(h.api.versions.value[0].id, 'fresh')
  154. h.unmount()
  155. })
  156. }
  157. test('loaded list clears synchronously; navigation only accepts a current list item', async () => {
  158. const h = mount()
  159. h.api.onShellReady()
  160. await detail(h)
  161. await rows(h)
  162. const item = h.api.versions.value[0]
  163. h.api.goView({ id: 'forged' })
  164. assert.deepEqual(h.navigation, [])
  165. h.api.goView(item)
  166. assert.equal(h.navigation[0].path, '/m/crm/quote/version-A')
  167. h.go(destination('B'))
  168. assert.deepEqual(h.api.versions.value, [])
  169. h.api.goView(item)
  170. assert.equal(h.navigation.length, 1)
  171. h.api.goBack()
  172. assert.deepEqual(h.navigation[1], { path: '/m/crm/quote/B', query: { from: 'manage' } })
  173. h.unmount()
  174. })
  175. for (const dest of [
  176. destination(''),
  177. destination('A', 'MpCrmQuoteDetail'),
  178. destination('B', 'MpCrmProductDetail')
  179. ]) {
  180. test(`invalid owner ${dest.name}/${dest.params.id} blocks reads and stale navigation`, async () => {
  181. const h = mount()
  182. h.api.onShellReady()
  183. h.go(dest)
  184. h.api.onShellReady()
  185. void h.api.loadVersions()
  186. h.api.goView({ id: 'A' })
  187. assert.equal(h.reads.length, 1)
  188. h.reads[0].resolve({ id: 'A', quoteNo: 'old' })
  189. await flush()
  190. assert.equal(h.reads.length, 1)
  191. assert.deepEqual(h.api.versions.value, [])
  192. assert.deepEqual(h.navigation, [])
  193. h.unmount()
  194. })
  195. }
  196. for (const stage of ['detail', 'versions'])
  197. for (const reject of [false, true]) {
  198. test(`unmount invalidates ${stage} success/error (${reject}) and entrypoints`, async () => {
  199. const h = mount()
  200. h.api.onShellReady()
  201. if (stage === 'versions') await detail(h)
  202. const count = h.reads.length
  203. h.unmount()
  204. if (reject) h.reads.at(-1).reject(new Error('late'))
  205. else
  206. h.reads.at(-1).resolve(stage === 'detail' ? { id: 'A', quoteNo: 'old' } : [{ id: 'old' }])
  207. await flush()
  208. h.api.onShellReady()
  209. void h.api.loadVersions()
  210. h.api.goView({ id: 'old' })
  211. assert.equal(h.reads.length, count)
  212. assert.deepEqual(h.api.versions.value, [])
  213. assert.equal(h.api.errorText.value, '')
  214. assert.deepEqual(h.navigation, [])
  215. })
  216. }
  217. test('wrong detail ID cannot query versions; retry recovers through failure and empty', async () => {
  218. const h = mount()
  219. h.api.onShellReady()
  220. h.reads[0].resolve({ id: 'wrong', quoteNo: 'old' })
  221. await flush()
  222. assert.equal(h.reads.length, 1)
  223. assert.ok(h.api.errorText.value)
  224. assert.equal(h.api.loading.value, false)
  225. void h.api.loadVersions()
  226. await detail(h)
  227. h.reads.at(-1).reject(new Error('offline'))
  228. await flush()
  229. assert.equal(h.api.errorText.value, 'offline')
  230. void h.api.loadVersions()
  231. assert.equal(h.api.errorText.value, '')
  232. await detail(h)
  233. await rows(h, [])
  234. assert.equal(h.api.errorText.value, '')
  235. assert.equal(h.api.loading.value, false)
  236. assert.deepEqual(h.api.versions.value, [])
  237. void h.api.loadVersions()
  238. await detail(h)
  239. await rows(h)
  240. assert.equal(h.api.versions.value.length, 1)
  241. h.unmount()
  242. })
  243. test('initial missing ID is visible and makes no request; a valid route recovers', async () => {
  244. const h = mount(destination(''))
  245. h.api.onShellReady()
  246. assert.equal(h.reads.length, 0)
  247. assert.equal(h.api.loading.value, false)
  248. assert.ok(h.api.errorText.value)
  249. h.go(destination('B'))
  250. assert.equal(h.reads[0].value, 'B')
  251. await detail(h)
  252. await rows(h)
  253. assert.equal(h.api.errorText.value, '')
  254. h.unmount()
  255. })
  256. test('missing quote number and first-stage failure remain retryable', async () => {
  257. const h = mount()
  258. h.api.onShellReady()
  259. h.reads[0].reject(new Error('detail unavailable'))
  260. await flush()
  261. assert.equal(h.api.errorText.value, 'detail unavailable')
  262. assert.equal(h.api.loading.value, false)
  263. void h.api.loadVersions()
  264. h.reads.at(-1).resolve({ id: 'A', quoteNo: ' ' })
  265. await flush()
  266. assert.equal(h.reads.length, 2)
  267. assert.equal(h.api.errorText.value, '无法获取报价单号')
  268. void h.api.loadVersions()
  269. await detail(h)
  270. await rows(h)
  271. assert.equal(h.api.errorText.value, '')
  272. h.unmount()
  273. })
  274. test('actual template renders failure, empty recovery and long names with amount helper', async () => {
  275. const { renderToString } = await import('vue/server-renderer')
  276. const render = vue.compile(descriptor.template!.content, { isCustomElement: () => true })
  277. const h = mount()
  278. const markup = () => {
  279. const context = vue.proxyRefs({ ...h.api, formatQuoteMoney, getMpQuoteAmountSummary })
  280. return renderToString(vue.createSSRApp({ render: () => render.call(context, context, []) }))
  281. }
  282. h.api.onShellReady()
  283. h.reads[0].reject(new Error('网络失败'))
  284. await flush()
  285. assert.match(await markup(), /网络失败/)
  286. assert.match(await markup(), /重试/)
  287. void h.api.loadVersions()
  288. await detail(h)
  289. await rows(h, [])
  290. assert.match(await markup(), /暂无版本历史/)
  291. assert.match(await markup(), /重新加载/)
  292. void h.api.loadVersions()
  293. await detail(h)
  294. const customerName = '客户ABCDEFGHIJKLMNOPQRSTUVWXYZ'.repeat(8)
  295. await rows(h, [{ id: 'version', version: 'V-LONG'.repeat(30), customerName, isLatest: 1 }])
  296. const html = await markup()
  297. assert.ok(html.includes(customerName))
  298. assert.match(html, /当前版本/)
  299. assert.match(html, /role="link"/)
  300. h.unmount()
  301. })