mobile-customer-detail-lifecycle.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. import assert from 'node:assert/strict'
  2. import test from 'node:test'
  3. import { readFileSync, existsSync } from 'node:fs'
  4. import { parse } from '@vue/compiler-sfc'
  5. import ts from 'typescript'
  6. import * as vue from 'vue'
  7. function deferred() {
  8. let resolve!: (value?: any) => void
  9. let reject!: (error: any) => void
  10. const promise = new Promise<any>((a, b) => {
  11. resolve = a
  12. reject = b
  13. })
  14. return { promise, resolve, reject }
  15. }
  16. const flush = async () => {
  17. for (let i = 0; i < 20; i++) await Promise.resolve()
  18. }
  19. // Execute actual script-setup functions inside Vue's renderer; API responses alone are deferred.
  20. const helperPath = new URL('../src/utils/mp-customer-panel-identity.ts', import.meta.url)
  21. function evaluate(page: string, props: any, overrides: Record<string, any>, events: any[]) {
  22. const source = parse(
  23. readFileSync(new URL(`../src/views/m/crm/customer/${page}.vue`, import.meta.url), 'utf8')
  24. ).descriptor.scriptSetup!.content
  25. const ast = ts.createSourceFile('panel.ts', source, ts.ScriptTarget.Latest, true)
  26. const vueEntries = Object.entries(vue).filter(
  27. ([k]) => /^[a-zA-Z_$][\w$]*$/.test(k) && k !== 'default'
  28. )
  29. const bindings: Record<string, any> = Object.fromEntries(vueEntries)
  30. delete bindings.default
  31. for (const statement of ast.statements) {
  32. if (!ts.isImportDeclaration(statement)) continue
  33. const clause = statement.importClause
  34. if (clause?.name) bindings[clause.name.text] = () => undefined
  35. if (clause?.namedBindings && ts.isNamedImports(clause.namedBindings))
  36. for (const item of clause.namedBindings.elements) bindings[item.name.text] = () => undefined
  37. }
  38. if (existsSync(helperPath)) {
  39. const helper = ts.transpile(
  40. readFileSync(helperPath, 'utf8').replace('export function', 'function'),
  41. { target: ts.ScriptTarget.ESNext }
  42. )
  43. bindings.useCustomerPanelIdentity = new Function(
  44. ...vueEntries.map(([k]) => k),
  45. `${helper};return useCustomerPanelIdentity`
  46. )(...vueEntries.map(([, v]) => v))
  47. }
  48. Object.assign(bindings, {
  49. defineProps: () => props,
  50. defineEmits:
  51. () =>
  52. (...args: any[]) =>
  53. events.push(args),
  54. defineExpose() {},
  55. useDictStore: () => ({ getOptions: () => [], getLabel: () => '', getTagType: () => '' }),
  56. unwrapRows: (v: any) => (Array.isArray(v) ? v : v?.data?.rows || v?.data || v?.rows || []),
  57. unwrapData: (v: any) => v?.data || v,
  58. canDeleteByCreator: () => true,
  59. contactFields: [{ key: 'contactName', required: true }],
  60. requiredFieldsError: () => '',
  61. contactDetailsError: () => '',
  62. showCrmConfirmDialog: async () => {},
  63. fetchContactByCustomerId: async () => [],
  64. fetchContactDetail: async (v: any) => v,
  65. ...overrides
  66. })
  67. const statements = ast.statements.filter((s) => !ts.isImportDeclaration(s))
  68. const names = statements.flatMap((s) =>
  69. ts.isFunctionDeclaration(s)
  70. ? [s.name!.text]
  71. : ts.isVariableStatement(s)
  72. ? s.declarationList.declarations.map((d) => d.name.getText(ast))
  73. : []
  74. )
  75. const code = ts.transpile(statements.map((s) => s.getText(ast)).join('\n'), {
  76. target: ts.ScriptTarget.ESNext
  77. })
  78. return new Function(...Object.keys(bindings), `${code};return {${names.join(',')}}`)(
  79. ...Object.values(bindings)
  80. )
  81. }
  82. const detailRoute = (id = 'A', tab = 'basic') => ({
  83. name: 'MpCrmCustomerDetail',
  84. path: `/m/crm/customer/${id}`,
  85. params: { id },
  86. query: { tab }
  87. })
  88. function mount(initial = detailRoute(), withChild = false) {
  89. const current = vue.shallowRef(initial)
  90. const route = Object.fromEntries(['name', 'path', 'params', 'query'].map((key) => [key, null]))
  91. for (const key of Object.keys(route))
  92. Object.defineProperty(route, key, { get: () => current.value[key] })
  93. const reads: any[] = [],
  94. writes: any[] = [],
  95. messages: any[] = [],
  96. navigation: any[] = []
  97. const confirm = deferred()
  98. let api: any
  99. let child: any
  100. const childRead = deferred()
  101. const childWrites: any[] = []
  102. const renderer = vue.createRenderer<any, any>({
  103. patchProp() {},
  104. insert() {},
  105. remove() {},
  106. createElement: () => ({}),
  107. createText: () => ({}),
  108. createComment: () => ({}),
  109. setText() {},
  110. setElementText() {},
  111. parentNode: () => null,
  112. nextSibling: () => null
  113. })
  114. const Child = vue.defineComponent({
  115. props: ['customerId', 'getIdentity'],
  116. setup(props) {
  117. child = evaluate(
  118. 'ContactPanel',
  119. props,
  120. {
  121. fetchContactByCustomerId: () => childRead.promise,
  122. showCrmConfirmDialog: () => confirm.promise,
  123. fetchDeleteContact: async (value: any) => childWrites.push(value)
  124. },
  125. []
  126. )
  127. return () => vue.h('div')
  128. }
  129. })
  130. const app = renderer.createApp({
  131. setup() {
  132. api = evaluate(
  133. 'detail',
  134. {},
  135. {
  136. useRoute: () => route,
  137. useRouter: () => ({
  138. replace: (v: any) => navigation.push(v),
  139. push: (v: any) => navigation.push(v)
  140. }),
  141. fetchCustomerDetail: (params: any) => {
  142. const d = deferred()
  143. reads.push({ ...d, params })
  144. return d.promise
  145. },
  146. fetchDeleteCustomer: (params: any) => {
  147. const d = deferred()
  148. writes.push({ ...d, params })
  149. return d.promise
  150. },
  151. showCrmConfirmDialog: () => confirm.promise,
  152. customerForm: (v: any) => v,
  153. showFailToast: (v: any) => messages.push(v),
  154. showSuccessToast: (v: any) => messages.push(v)
  155. },
  156. []
  157. )
  158. return () =>
  159. withChild && api.customer.value && !api.loading.value
  160. ? vue.h(Child, { customerId: api.id.value, getIdentity: api.getPanelIdentity })
  161. : vue.h('div')
  162. }
  163. })
  164. app.mount({})
  165. return {
  166. api,
  167. reads,
  168. writes,
  169. messages,
  170. navigation,
  171. confirm,
  172. childRead,
  173. childWrites,
  174. get child() {
  175. return child
  176. },
  177. go: (value: any) => {
  178. current.value = value
  179. },
  180. unmount: () => app.unmount()
  181. }
  182. }
  183. const destinations = [
  184. { name: 'MpCrmCustomerList', path: '/m/crm/customer', params: {}, query: {} },
  185. { name: 'MpCrmProductDetail', path: '/m/crm/product/B', params: { id: 'B' }, query: {} },
  186. { name: 'MpCrmProductDetail', path: '/m/crm/product/A', params: { id: 'A' }, query: {} },
  187. { name: 'MpCrmCustomerEdit', path: '/m/crm/customer/A/edit', params: { id: 'A' }, query: {} },
  188. detailRoute('')
  189. ]
  190. for (const destination of destinations) {
  191. test(`leave to ${destination.name}/${destination.params.id || 'empty'} blocks all reads and invalidates synchronously`, async () => {
  192. const h = mount()
  193. h.api.onReady()
  194. const key = h.api.getPanelIdentity()
  195. h.go(destination)
  196. assert.notEqual(h.api.getPanelIdentity(), key)
  197. assert.equal(h.reads.length, 1, 'leaving must not request a customer')
  198. await h.api.load()
  199. await h.api.load('A')
  200. await h.api.refreshInfo()
  201. h.api.onReady()
  202. assert.equal(h.reads.length, 1)
  203. h.reads[0].resolve({ id: 'A', customerName: 'stale' })
  204. await flush()
  205. assert.equal(h.api.customer.value, undefined)
  206. assert.equal(h.api.error.value, '')
  207. assert.deepEqual(h.messages, [])
  208. h.unmount()
  209. })
  210. }
  211. test('ready gate, same-ID tab/query changes, retries and same-path reloads', async () => {
  212. const h = mount()
  213. await h.api.load()
  214. await h.api.refreshInfo()
  215. h.go(detailRoute('B'))
  216. assert.equal(h.reads.length, 0)
  217. h.api.onReady()
  218. h.api.onReady()
  219. assert.equal(h.reads.length, 1)
  220. assert.equal(h.reads[0].params.id, 'B')
  221. h.go(detailRoute('B', 'contact'))
  222. assert.equal(h.api.tab.value, 'contact')
  223. assert.equal(h.reads.length, 1)
  224. h.reads[0].reject(new Error('retryable'))
  225. await flush()
  226. assert.equal(h.api.error.value, 'retryable')
  227. const retry = h.api.load()
  228. h.reads[1].resolve({ id: 'B' })
  229. await retry
  230. const reload = h.api.load()
  231. h.reads[2].resolve({ id: 'B' })
  232. await reload
  233. const refresh = h.api.refreshInfo()
  234. h.reads[3].resolve({ id: 'B', customerName: 'fresh' })
  235. await refresh
  236. assert.equal(h.api.customer.value.customerName, 'fresh')
  237. h.unmount()
  238. })
  239. for (const aba of [false, true])
  240. for (const rejectOld of [false, true]) {
  241. test(`latest route wins: ABA=${aba} reject=${rejectOld}`, async () => {
  242. const h = mount()
  243. h.api.onReady()
  244. h.go(detailRoute('B'))
  245. if (aba) h.go(detailRoute('A'))
  246. const latest = h.reads.at(-1)
  247. for (const read of h.reads.slice(0, -1)) {
  248. if (rejectOld) read.reject(new Error('old failure'))
  249. else read.resolve({ id: read.params.id, customerName: 'stale' })
  250. }
  251. await flush()
  252. assert.equal(h.api.loading.value, true)
  253. assert.equal(h.api.error.value, '')
  254. assert.equal(h.api.customer.value, undefined)
  255. latest.resolve({ id: latest.params.id, customerName: 'latest' })
  256. await flush()
  257. assert.equal(h.api.customer.value.customerName, 'latest')
  258. h.unmount()
  259. })
  260. }
  261. for (const afterWrite of [false, true])
  262. test(`same-ID leave invalidates pending delete (write started=${afterWrite})`, async () => {
  263. const h = mount()
  264. h.api.onReady()
  265. h.reads[0].resolve({ id: 'A' })
  266. await flush()
  267. const pending = h.api.remove()
  268. if (afterWrite) {
  269. h.confirm.resolve()
  270. await flush()
  271. assert.equal(h.writes.length, 1)
  272. }
  273. h.go(destinations[2])
  274. h.confirm.resolve()
  275. await flush()
  276. for (const write of h.writes) write.resolve()
  277. await pending
  278. assert.equal(h.writes.length, afterWrite ? 1 : 0)
  279. assert.deepEqual(h.messages, [])
  280. assert.deepEqual(h.navigation, [])
  281. h.api.goEdit()
  282. assert.deepEqual(h.navigation, [])
  283. h.unmount()
  284. })
  285. for (const destination of destinations)
  286. test(`late ready outside valid detail: ${destination.name}/${destination.params.id || 'empty'}`, async () => {
  287. const h = mount()
  288. h.go(destination)
  289. h.api.onReady()
  290. assert.equal(h.reads.length, 0)
  291. h.unmount()
  292. })
  293. test('refresh failure after same-ID leave is silent; reentry can load', async () => {
  294. const h = mount()
  295. h.api.onReady()
  296. h.reads[0].resolve({ id: 'A' })
  297. await flush()
  298. const refresh = h.api.refreshInfo()
  299. h.go(destinations[2])
  300. h.reads[1].reject(new Error('old refresh'))
  301. await refresh
  302. assert.deepEqual(h.messages, [])
  303. h.go(detailRoute())
  304. assert.equal(h.reads.length, 3)
  305. h.reads[2].resolve({ id: 'A', customerName: 'back' })
  306. await flush()
  307. assert.equal(h.api.customer.value.customerName, 'back')
  308. h.unmount()
  309. })
  310. test('same-ID leave invalidates real child panel reads and confirmations before unmount', async () => {
  311. const h = mount(detailRoute(), true)
  312. h.api.onReady()
  313. h.reads[0].resolve({ id: 'A' })
  314. await flush()
  315. const child = h.child
  316. const pending = child.remove({ id: 'contact-A' })
  317. h.confirm.resolve()
  318. h.childRead.resolve([{ id: 'stale' }])
  319. h.go(destinations[2])
  320. assert.deepEqual(child.rows.value, [])
  321. assert.equal(child.acting.value, false)
  322. await pending
  323. await flush()
  324. assert.deepEqual(h.childWrites, [])
  325. assert.deepEqual(child.rows.value, [])
  326. h.unmount()
  327. })
  328. test('unmount makes pending reads and all entry points inert', async () => {
  329. const h = mount()
  330. h.api.onReady()
  331. h.unmount()
  332. h.reads[0].reject(new Error('late'))
  333. await flush()
  334. await h.api.load()
  335. await h.api.refreshInfo()
  336. h.api.onReady()
  337. assert.equal(h.reads.length, 1)
  338. assert.equal(h.api.error.value, '')
  339. assert.deepEqual(h.messages, [])
  340. })