teamBackgroundFile.test.js 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630
  1. const assert = require('node:assert/strict')
  2. const fs = require('node:fs')
  3. const path = require('node:path')
  4. const { pathToFileURL } = require('node:url')
  5. const vm = require('node:vm')
  6. const rules = require('../utils/teamBackgroundFile')
  7. assert.equal(rules.validateEnterpriseWebsite(' 无 '), '')
  8. assert.equal(rules.validateEnterpriseWebsite('https://example.com'), '')
  9. assert.match(rules.validateEnterpriseWebsite('ftp://example.com'), /http/)
  10. const websiteWithLength = length => `https://example.com/${'a'.repeat(length - 20)}`
  11. assert.equal(rules.validateEnterpriseWebsite(websiteWithLength(499)), '')
  12. assert.equal(rules.validateEnterpriseWebsite(websiteWithLength(500)), '')
  13. assert.match(rules.validateEnterpriseWebsite(websiteWithLength(501)), /500/)
  14. assert.equal(rules.validateBackgroundFile({ name: 'brief.PDF', size: 1 }), '')
  15. assert.match(rules.validateBackgroundFile({ name: 'brief.zip', size: 1 }), /类型/)
  16. assert.match(rules.validateBackgroundFile({ name: 'brief.pdf', size: 50 * 1024 * 1024 + 1 }), /50MB/)
  17. assert.equal(rules.validateBackgroundFile({ name: 'brief.pdf', size: 50 * 1024 * 1024 }), '')
  18. assert.equal(rules.validateBackgroundFile({ name: `${'a'.repeat(251)}.pdf`, size: 1 }), '')
  19. assert.match(rules.validateBackgroundFile({ name: `${'a'.repeat(252)}.pdf`, size: 1 }), /255/)
  20. assert.match(rules.validateBackgroundFile({ name: 'empty.pdf', size: 0 }), /非空/)
  21. const backendExpiry = '2026-07-21 15:30:00'
  22. const explicitOffsetExpiry = '2026-07-21T15:30:00+08:00'
  23. const utcExpiry = '2026-07-21T07:30:00.250Z'
  24. assert.equal(rules.parseSessionExpiresAt(backendExpiry), Date.UTC(2026, 6, 21, 7, 30, 0))
  25. assert.equal(rules.parseSessionExpiresAt(explicitOffsetExpiry), Date.UTC(2026, 6, 21, 7, 30, 0))
  26. assert.equal(rules.parseSessionExpiresAt(utcExpiry), Date.UTC(2026, 6, 21, 7, 30, 0, 250))
  27. assert.equal(rules.getSessionRemainingSeconds(backendExpiry, Date.UTC(2026, 6, 21, 7, 29, 59, 1)), 1)
  28. assert.equal(rules.getSessionRemainingSeconds(backendExpiry, Date.UTC(2026, 6, 21, 7, 30, 1)), 0)
  29. assert.equal(rules.getSessionRemainingSeconds('2026-07-21T15:30:00', 0), 0)
  30. assert.equal(rules.getSessionRemainingSeconds('not-a-date', 0), 0)
  31. const validQueueItem = rules.createBackgroundQueueItem(
  32. { name: 'brief.pdf', path: '/tmp/brief.pdf', size: 1 },
  33. 'valid-file'
  34. )
  35. const invalidQueueItem = rules.createBackgroundQueueItem(
  36. { name: 'archive.zip', path: '/tmp/archive.zip', size: 1 },
  37. 'invalid-file'
  38. )
  39. assert.equal(validQueueItem.status, 'pending')
  40. assert.equal(validQueueItem.progress, 0)
  41. assert.equal(validQueueItem.validationError, '')
  42. assert.equal(invalidQueueItem.status, 'failed')
  43. assert.match(invalidQueueItem.validationError, /类型/)
  44. validQueueItem.status = 'success'
  45. const uploadFailure = {
  46. id: 'upload-failure',
  47. status: 'failed',
  48. validationError: '',
  49. error: '上传失败'
  50. }
  51. assert.deepEqual(
  52. rules.getUploadableBackgroundFiles([validQueueItem, invalidQueueItem, uploadFailure]),
  53. [uploadFailure]
  54. )
  55. const originalTeam = {
  56. id: 12,
  57. teamName: '研发团队',
  58. enterpriseWebsite: ' https://example.com/team ',
  59. coachId: 3,
  60. uploaderId: 4,
  61. source: 'WECHAT'
  62. }
  63. const teamSubmitPayload = rules.createTeamSubmitPayload(originalTeam)
  64. assert.equal(teamSubmitPayload.id, 12)
  65. assert.equal(teamSubmitPayload.enterpriseWebsite, 'https://example.com/team')
  66. assert.equal(Object.hasOwn(teamSubmitPayload, 'coachId'), false)
  67. assert.equal(Object.hasOwn(teamSubmitPayload, 'uploaderId'), false)
  68. assert.equal(Object.hasOwn(teamSubmitPayload, 'source'), false)
  69. assert.equal(originalTeam.coachId, 3, 'payload creation must not mutate the displayed detail')
  70. const textPreviewState = rules.createTextPreviewState({
  71. mode: 'text',
  72. fileName: '背景说明.md',
  73. content: '# 团队背景',
  74. truncated: true
  75. }, 'fallback.md')
  76. assert.deepEqual(textPreviewState, {
  77. visible: true,
  78. fileName: '背景说明.md',
  79. content: '# 团队背景',
  80. truncated: true
  81. })
  82. assert.deepEqual(rules.createEmptyTextPreviewState(), {
  83. visible: false,
  84. fileName: '',
  85. content: '',
  86. truncated: false
  87. })
  88. assert.notEqual(rules.createEmptyTextPreviewState(), rules.createEmptyTextPreviewState())
  89. const creationState = rules.createTeamCreationState()
  90. assert.deepEqual(creationState, {
  91. createdTeamId: '',
  92. submitting: false,
  93. stage: 'idle',
  94. completed: false,
  95. teamPayloadSnapshot: '',
  96. teamQuestionnaireId: '',
  97. publishResult: null,
  98. resumeStage: ''
  99. })
  100. const firstPayloadSnapshot = rules.createTeamPayloadSnapshot({
  101. teamName: '团队', enterpriseWebsite: ' https://example.com ', coachId: 7
  102. })
  103. const equivalentPayloadSnapshot = rules.createTeamPayloadSnapshot({
  104. enterpriseWebsite: 'https://example.com', teamName: '团队'
  105. })
  106. assert.equal(firstPayloadSnapshot, equivalentPayloadSnapshot)
  107. assert.notEqual(firstPayloadSnapshot, rules.createTeamPayloadSnapshot({
  108. teamName: '团队', enterpriseWebsite: 'https://changed.example.com'
  109. }))
  110. assert.equal(rules.beginTeamSubmission(creationState), true)
  111. assert.equal(rules.beginTeamSubmission(creationState), false, 'a second submission must be locked')
  112. assert.equal(rules.rememberCreatedTeam(creationState, 88), 88)
  113. assert.equal(rules.rememberCreatedTeam(creationState, 99), 88, 'the first server team id must be retained')
  114. rules.setTeamSubmissionStage(creationState, 'upload')
  115. assert.equal(creationState.stage, 'upload')
  116. rules.finishTeamSubmission(creationState)
  117. assert.equal(creationState.submitting, false)
  118. assert.equal(rules.beginTeamSubmission(creationState), true, 'a failed later stage can resume')
  119. rules.finishTeamSubmission(creationState, true)
  120. assert.equal(creationState.completed, true)
  121. assert.equal(rules.beginTeamSubmission(creationState), false, 'a completed flow cannot be scheduled twice')
  122. assert.equal(rules.hasUnresolvedBackgroundFiles([
  123. { status: 'success', validationError: '' },
  124. { status: 'failed', validationError: '文件类型不支持' }
  125. ]), false)
  126. for (const item of [
  127. { status: 'pending', validationError: '' },
  128. { status: 'uploading', validationError: '' },
  129. { status: 'failed', validationError: '' }
  130. ]) {
  131. assert.equal(rules.hasUnresolvedBackgroundFiles([item]), true)
  132. }
  133. console.log('team background rules: PASS')
  134. const transportPath = path.join(__dirname, '../http/teamBackgroundFile.js')
  135. const httpInterfacePath = path.join(__dirname, '../http/interface.js')
  136. const httpIndexPath = path.join(__dirname, '../http/index.js')
  137. async function loadTransport({ api = {}, uni = {}, wx = {} } = {}) {
  138. const source = fs.readFileSync(transportPath, 'utf8')
  139. const context = vm.createContext({ uni, wx })
  140. const baseApiModule = new vm.SyntheticModule(['BaseApi'], function () {
  141. this.setExport('BaseApi', 'https://api.example.test/app')
  142. }, { context, identifier: 'test:baseApi' })
  143. const apiModule = new vm.SyntheticModule(['default'], function () {
  144. this.setExport('default', api)
  145. }, { context, identifier: 'test:api' })
  146. const transportModule = new vm.SourceTextModule(source, {
  147. context,
  148. identifier: pathToFileURL(transportPath).href
  149. })
  150. await transportModule.link(specifier => {
  151. if (specifier === './baseApi.js') return baseApiModule
  152. if (specifier === './index.js') return apiModule
  153. throw new Error(`unexpected transport import: ${specifier}`)
  154. })
  155. await transportModule.evaluate()
  156. return transportModule.namespace
  157. }
  158. async function loadHttpApi(uni) {
  159. const context = vm.createContext({
  160. uni,
  161. process: { env: { NODE_ENV: 'test' } }
  162. })
  163. const baseApiModule = new vm.SyntheticModule(['BaseApi'], function () {
  164. this.setExport('BaseApi', 'https://api.example.test/app')
  165. }, { context, identifier: 'test:httpBaseApi' })
  166. const interfaceModule = new vm.SourceTextModule(
  167. fs.readFileSync(httpInterfacePath, 'utf8'),
  168. { context, identifier: pathToFileURL(httpInterfacePath).href }
  169. )
  170. const indexModule = new vm.SourceTextModule(
  171. fs.readFileSync(httpIndexPath, 'utf8'),
  172. { context, identifier: pathToFileURL(httpIndexPath).href }
  173. )
  174. await indexModule.link((specifier, referencingModule) => {
  175. if (referencingModule === indexModule && specifier === './interface') return interfaceModule
  176. if (referencingModule === interfaceModule && specifier === './baseApi.js') return baseApiModule
  177. throw new Error(`unexpected http import: ${specifier}`)
  178. })
  179. await indexModule.evaluate()
  180. return indexModule.namespace.default
  181. }
  182. async function testConcurrentSilentRequestDoesNotStrandLoadingMask() {
  183. const requests = []
  184. let shown = 0
  185. let hidden = 0
  186. const api = await loadHttpApi({
  187. showLoading() { shown += 1 },
  188. hideLoading() { hidden += 1 },
  189. getStorageSync() { return '' },
  190. request(options) { requests.push(options) }
  191. })
  192. const visibleRequest = api.get('/visible', {}, true)
  193. const silentRequest = api.get('/silent', {}, false)
  194. assert.equal(shown, 1)
  195. assert.equal(hidden, 0)
  196. assert.equal(requests.length, 2)
  197. requests[1].complete({ statusCode: 200, data: { code: 0, data: [] } })
  198. await silentRequest
  199. assert.equal(hidden, 0, 'a silent request must not hide another request loading mask')
  200. requests[0].complete({ statusCode: 200, data: { code: 0, data: {} } })
  201. await visibleRequest
  202. assert.equal(hidden, 1, 'the request that displayed loading must always hide it on completion')
  203. }
  204. function assertNoIdentityFields(value) {
  205. if (!value || typeof value !== 'object') return
  206. for (const [key, child] of Object.entries(value)) {
  207. assert.ok(!['source', 'coachId', 'uploaderId'].includes(key), `unexpected identity field: ${key}`)
  208. assertNoIdentityFields(child)
  209. }
  210. }
  211. async function createUploadHarness(response, progress = 37) {
  212. let request
  213. const progressValues = []
  214. const uni = {
  215. getStorageSync(key) {
  216. assert.equal(key, 'token')
  217. return 'token-123'
  218. },
  219. uploadFile(options) {
  220. request = options
  221. return {
  222. onProgressUpdate(callback) {
  223. callback({ progress })
  224. setImmediate(() => options.success(response))
  225. }
  226. }
  227. }
  228. }
  229. const transport = await loadTransport({ uni })
  230. return {
  231. request: () => request,
  232. progressValues,
  233. promise: transport.uploadTeamBackgroundFile(12, '/tmp/brief.pdf', value => progressValues.push(value))
  234. }
  235. }
  236. async function testUploadTransport() {
  237. const stringHarness = await createUploadHarness({
  238. statusCode: 200,
  239. data: JSON.stringify({ code: 0, data: { id: 7 } })
  240. })
  241. assert.equal((await stringHarness.promise).id, 7)
  242. assert.equal(stringHarness.request().url, 'https://api.example.test/app/core/user/team/12/background-files')
  243. assert.equal(stringHarness.request().filePath, '/tmp/brief.pdf')
  244. assert.equal(stringHarness.request().name, 'file')
  245. assert.equal(stringHarness.request().header.token, 'token-123')
  246. assert.deepEqual(stringHarness.progressValues, [37])
  247. assertNoIdentityFields(stringHarness.request())
  248. const objectHarness = await createUploadHarness({ statusCode: 200, data: { code: 0, data: { id: 8 } } })
  249. assert.equal((await objectHarness.promise).id, 8)
  250. const statusHarness = await createUploadHarness({ statusCode: 500, data: { code: 0 } })
  251. await assert.rejects(statusHarness.promise, /上传失败,请重试/)
  252. const codeHarness = await createUploadHarness({ statusCode: 200, data: { code: 9, msg: '上传业务失败' } })
  253. await assert.rejects(codeHarness.promise, /上传业务失败/)
  254. const invalidJsonHarness = await createUploadHarness({ statusCode: 200, data: '<invalid-json>' })
  255. await assert.rejects(invalidJsonHarness.promise, /上传失败,请重试/)
  256. }
  257. async function testApiTransport() {
  258. const calls = []
  259. const api = {
  260. get(...args) {
  261. calls.push(['get', ...args])
  262. return Promise.resolve({ data: { code: 0, data: [{ id: 1 }] } })
  263. },
  264. del(...args) {
  265. calls.push(['del', ...args])
  266. return Promise.resolve({ data: { code: 0, data: true } })
  267. },
  268. post(...args) {
  269. calls.push(['post', ...args])
  270. return Promise.resolve({ data: { code: 0, data: { sessionId: 'session-1' } } })
  271. }
  272. }
  273. const transport = await loadTransport({ api })
  274. assert.deepEqual(await transport.listTeamBackgroundFiles(12), [{ id: 1 }])
  275. assert.equal(await transport.disableTeamBackgroundFile(12, 34), true)
  276. assert.deepEqual(await transport.createTeamBackgroundSession(12), { sessionId: 'session-1' })
  277. assert.equal(calls[0][0], 'get')
  278. assert.equal(calls[0][1], '/core/user/team/12/background-files')
  279. assert.equal(calls[1][0], 'del')
  280. assert.equal(calls[1][1], '/core/user/team/12/background-files/34')
  281. assert.equal(calls[2][0], 'post')
  282. assert.equal(calls[2][1], '/core/user/team/12/background-upload-session')
  283. for (const call of calls) {
  284. assert.equal(Object.keys(call[2]).length, 0)
  285. assert.equal(call[3], false)
  286. assertNoIdentityFields(call)
  287. }
  288. const failingTransport = await loadTransport({
  289. api: {
  290. get: () => Promise.resolve({ data: { code: 3, msg: '列表业务失败' } })
  291. }
  292. })
  293. await assert.rejects(failingTransport.listTeamBackgroundFiles(12), /列表业务失败/)
  294. assert.equal(transport.uploadTeamBackgroundFile.length, 2)
  295. assert.equal(transport.listTeamBackgroundFiles.length, 1)
  296. assert.equal(transport.disableTeamBackgroundFile.length, 2)
  297. assert.equal(transport.createTeamBackgroundSession.length, 1)
  298. assert.equal(transport.downloadTeamBackgroundFile.length, 2)
  299. }
  300. const TEXT_PREVIEW_LIMIT = 256 * 1024
  301. async function createDownloadHarness({ result, responseHeaders, downloadError, openError,
  302. fileSize, fileContent = '', fileInfoError, readError, withHeadersListener = true } = {}) {
  303. let request
  304. let openRequest
  305. let fileInfoRequest
  306. let readRequest
  307. let fileSystemManagerCalls = 0
  308. const resolvedFileSize = fileSize === undefined
  309. ? Buffer.byteLength(fileContent, 'utf8')
  310. : fileSize
  311. const uni = {
  312. getStorageSync(key) {
  313. assert.equal(key, 'token')
  314. return 'token-456'
  315. },
  316. downloadFile(options) {
  317. request = options
  318. setImmediate(() => {
  319. if (downloadError) options.fail(downloadError)
  320. else options.success(result)
  321. })
  322. if (!withHeadersListener) return {}
  323. return {
  324. onHeadersReceived(callback) {
  325. if (responseHeaders) callback({ header: responseHeaders })
  326. }
  327. }
  328. }
  329. }
  330. const wx = {
  331. openDocument(options) {
  332. openRequest = options
  333. setImmediate(() => {
  334. if (openError) options.fail(openError)
  335. else options.success('opened')
  336. })
  337. },
  338. getFileSystemManager() {
  339. fileSystemManagerCalls += 1
  340. return {
  341. getFileInfo(options) {
  342. fileInfoRequest = options
  343. setImmediate(() => {
  344. if (fileInfoError) options.fail(fileInfoError)
  345. else options.success({ size: resolvedFileSize })
  346. })
  347. },
  348. readFile(options) {
  349. readRequest = options
  350. setImmediate(() => {
  351. if (readError) options.fail(readError)
  352. else options.success({ data: fileContent })
  353. })
  354. }
  355. }
  356. }
  357. }
  358. const transport = await loadTransport({ uni, wx })
  359. return {
  360. request: () => request,
  361. openRequest: () => openRequest,
  362. fileInfoRequest: () => fileInfoRequest,
  363. readRequest: () => readRequest,
  364. fileSystemManagerCalls: () => fileSystemManagerCalls,
  365. promise: transport.downloadTeamBackgroundFile(12, 34)
  366. }
  367. }
  368. async function testDownloadTransport() {
  369. const successHarness = await createDownloadHarness({
  370. result: { statusCode: 200, tempFilePath: '/tmp/download.pdf' },
  371. responseHeaders: {
  372. 'cOnTeNt-TyPe': 'application/pdf',
  373. 'CONTENT-disPOSITION': 'attachment; filename="download.pdf"'
  374. }
  375. })
  376. const documentPreview = await successHarness.promise
  377. assert.equal(documentPreview.mode, 'document')
  378. assert.equal(documentPreview.fileName, 'download.pdf')
  379. assert.equal(documentPreview.filePath, '/tmp/download.pdf')
  380. assert.equal(successHarness.request().url, 'https://api.example.test/app/core/user/team/12/background-files/34/download')
  381. assert.equal(successHarness.request().header.token, 'token-456')
  382. assert.equal(successHarness.openRequest(), undefined, 'transport must not open a document before component context checks')
  383. assertNoIdentityFields(successHarness.request())
  384. const resultHeaderHarness = await createDownloadHarness({
  385. result: {
  386. statusCode: 200,
  387. tempFilePath: '/tmp/result-header.docx',
  388. header: {
  389. 'content-type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  390. 'content-disposition': 'attachment; filename="result-header.docx"'
  391. }
  392. },
  393. withHeadersListener: false
  394. })
  395. const resultHeaderPreview = await resultHeaderHarness.promise
  396. assert.equal(resultHeaderPreview.mode, 'document')
  397. assert.equal(resultHeaderPreview.fileName, 'result-header.docx')
  398. assert.equal(resultHeaderPreview.filePath, '/tmp/result-header.docx')
  399. assert.equal(resultHeaderHarness.openRequest(), undefined)
  400. assert.equal(resultHeaderHarness.fileSystemManagerCalls(), 0)
  401. const txtHarness = await createDownloadHarness({
  402. result: {
  403. statusCode: 200,
  404. tempFilePath: '/tmp/text-preview.txt',
  405. headers: {
  406. 'Content-Type': 'text/plain; charset=UTF-8',
  407. 'Content-Disposition': 'attachment; filename="fallback.txt"; '
  408. + "filename*=UTF-8''%E8%83%8C%E6%99%AF%20%E8%B5%84%E6%96%99.txt"
  409. }
  410. },
  411. fileSize: 5,
  412. fileContent: 'hello',
  413. withHeadersListener: false
  414. })
  415. const txtPreview = await txtHarness.promise
  416. assert.equal(txtHarness.openRequest(), undefined, 'txt must not call openDocument')
  417. assert.equal(txtPreview.mode, 'text')
  418. assert.equal(txtPreview.fileName, '背景 资料.txt')
  419. assert.equal(txtPreview.content, 'hello')
  420. assert.equal(txtPreview.truncated, false)
  421. assert.equal(txtHarness.fileInfoRequest().filePath, '/tmp/text-preview.txt')
  422. assert.equal(txtHarness.readRequest().filePath, '/tmp/text-preview.txt')
  423. assert.equal(txtHarness.readRequest().encoding, 'utf8')
  424. assert.equal(txtHarness.readRequest().position, 0)
  425. assert.equal(txtHarness.readRequest().length, 5)
  426. const emptyTextHarness = await createDownloadHarness({
  427. result: { statusCode: 200, tempFilePath: '/tmp/empty.txt' },
  428. responseHeaders: {
  429. 'Content-Type': 'text/plain',
  430. 'Content-Disposition': 'attachment; filename="empty.txt"'
  431. },
  432. fileSize: 0
  433. })
  434. const emptyTextPreview = await emptyTextHarness.promise
  435. assert.equal(emptyTextPreview.mode, 'text')
  436. assert.equal(emptyTextPreview.fileName, 'empty.txt')
  437. assert.equal(emptyTextPreview.content, '')
  438. assert.equal(emptyTextPreview.truncated, false)
  439. assert.equal(emptyTextHarness.readRequest(), undefined)
  440. const invalidEncodedNameHarness = await createDownloadHarness({
  441. result: { statusCode: 200, tempFilePath: '/tmp/fallback.txt' },
  442. responseHeaders: {
  443. 'Content-Type': 'text/plain',
  444. 'Content-Disposition': 'attachment; filename="fallback.txt"; '
  445. + "filename*=UTF-8''%E0%A4%A"
  446. },
  447. fileSize: 8,
  448. fileContent: 'fallback'
  449. })
  450. const invalidEncodedNamePreview = await invalidEncodedNameHarness.promise
  451. assert.equal(invalidEncodedNamePreview.fileName, 'fallback.txt')
  452. assert.equal(invalidEncodedNamePreview.content, 'fallback')
  453. const mdContent = 'm'.repeat(TEXT_PREVIEW_LIMIT)
  454. const mdHarness = await createDownloadHarness({
  455. result: { statusCode: 200, tempFilePath: '/tmp/guide.md' },
  456. responseHeaders: {
  457. 'Content-Type': 'text/markdown; charset=UTF-8',
  458. 'Content-Disposition': 'attachment; filename="guide.md"'
  459. },
  460. fileSize: 50 * 1024 * 1024,
  461. fileContent: mdContent
  462. })
  463. const mdPreview = await mdHarness.promise
  464. assert.equal(mdHarness.openRequest(), undefined)
  465. assert.equal(mdPreview.mode, 'text')
  466. assert.equal(mdPreview.fileName, 'guide.md')
  467. assert.equal(mdPreview.content.length, TEXT_PREVIEW_LIMIT)
  468. assert.equal(mdPreview.truncated, true)
  469. assert.equal(mdHarness.readRequest().length, TEXT_PREVIEW_LIMIT)
  470. const csvContent = 'c'.repeat(TEXT_PREVIEW_LIMIT)
  471. const csvHarness = await createDownloadHarness({
  472. result: { statusCode: 200, tempFilePath: '/tmp/data.csv' },
  473. responseHeaders: {
  474. 'Content-Type': 'text/csv',
  475. 'Content-Disposition': 'attachment; filename=data.csv'
  476. },
  477. fileSize: TEXT_PREVIEW_LIMIT,
  478. fileContent: csvContent
  479. })
  480. const csvPreview = await csvHarness.promise
  481. assert.equal(csvHarness.openRequest(), undefined)
  482. assert.equal(csvPreview.mode, 'text')
  483. assert.equal(csvPreview.fileName, 'data.csv')
  484. assert.equal(csvPreview.content.length, TEXT_PREVIEW_LIMIT)
  485. assert.equal(csvPreview.truncated, false)
  486. assert.equal(csvHarness.readRequest().length, TEXT_PREVIEW_LIMIT)
  487. const fileInfoFailureHarness = await createDownloadHarness({
  488. result: { statusCode: 200, tempFilePath: '/tmp/file-info-failure.txt' },
  489. responseHeaders: {
  490. 'Content-Type': 'text/plain',
  491. 'Content-Disposition': 'attachment; filename="file-info-failure.txt"'
  492. },
  493. fileInfoError: new Error('getFileInfo failed')
  494. })
  495. await assert.rejects(fileInfoFailureHarness.promise, /文件读取失败,请重试/)
  496. assert.equal(fileInfoFailureHarness.openRequest(), undefined)
  497. assert.equal(fileInfoFailureHarness.readRequest(), undefined)
  498. const readFailureHarness = await createDownloadHarness({
  499. result: { statusCode: 200, tempFilePath: '/tmp/read-failure.md' },
  500. responseHeaders: {
  501. 'Content-Type': 'text/markdown',
  502. 'Content-Disposition': 'attachment; filename="read-failure.md"'
  503. },
  504. fileSize: 10,
  505. readError: new Error('readFile failed')
  506. })
  507. await assert.rejects(readFailureHarness.promise, /文件读取失败,请重试/)
  508. assert.equal(readFailureHarness.openRequest(), undefined)
  509. const unknownExtensionHarness = await createDownloadHarness({
  510. result: { statusCode: 200, tempFilePath: '/tmp/unknown-file' },
  511. responseHeaders: {
  512. 'Content-Type': 'application/octet-stream',
  513. 'Content-Disposition': 'attachment; filename="archive.zip"'
  514. }
  515. })
  516. await assert.rejects(unknownExtensionHarness.promise, /文件类型不支持预览/)
  517. assert.equal(unknownExtensionHarness.openRequest(), undefined)
  518. assert.equal(unknownExtensionHarness.fileSystemManagerCalls(), 0)
  519. const jsonHarness = await createDownloadHarness({
  520. result: { statusCode: 200, tempFilePath: '/tmp/error.json' },
  521. responseHeaders: {
  522. 'Content-Type': 'application/json;charset=UTF-8',
  523. 'Content-Disposition': 'attachment; filename="error.json"'
  524. }
  525. })
  526. await assert.rejects(jsonHarness.promise, /下载失败,请重试/)
  527. assert.equal(jsonHarness.openRequest(), undefined)
  528. const htmlHarness = await createDownloadHarness({
  529. result: { statusCode: 200, tempFilePath: '/tmp/error.html' },
  530. responseHeaders: {
  531. 'content-type': 'text/html; charset=UTF-8',
  532. 'content-disposition': 'attachment; filename="error.html"'
  533. }
  534. })
  535. await assert.rejects(htmlHarness.promise, /下载失败,请重试/)
  536. assert.equal(htmlHarness.openRequest(), undefined)
  537. const missingHeadersHarness = await createDownloadHarness({
  538. result: { statusCode: 200, tempFilePath: '/tmp/unknown.pdf' },
  539. withHeadersListener: false
  540. })
  541. await assert.rejects(missingHeadersHarness.promise, /下载失败,请重试/)
  542. assert.equal(missingHeadersHarness.openRequest(), undefined)
  543. const statusHarness = await createDownloadHarness({ result: { statusCode: 500 } })
  544. await assert.rejects(statusHarness.promise, /下载失败,请重试/)
  545. assert.equal(statusHarness.openRequest(), undefined)
  546. const downloadError = new Error('download network error')
  547. const downloadFailureHarness = await createDownloadHarness({ downloadError })
  548. await assert.rejects(downloadFailureHarness.promise, /download network error/)
  549. const noTransportOpenHarness = await createDownloadHarness({
  550. result: { statusCode: 200, tempFilePath: '/tmp/download.pdf' },
  551. responseHeaders: {
  552. 'Content-Type': 'application/pdf',
  553. 'Content-Disposition': 'attachment; filename="download.pdf"'
  554. },
  555. openError: new Error('must not be reached')
  556. })
  557. assert.equal((await noTransportOpenHarness.promise).mode, 'document')
  558. assert.equal(noTransportOpenHarness.openRequest(), undefined)
  559. }
  560. function readSfcScript(filePath) {
  561. const source = fs.readFileSync(filePath, 'utf8')
  562. const openingTag = '<script>'
  563. const start = source.indexOf(openingTag)
  564. const end = source.indexOf('</script>', start + openingTag.length)
  565. if (start < 0 || end < 0) throw new Error(`missing script block: ${filePath}`)
  566. return source.slice(start + openingTag.length, end)
  567. }
  568. async function loadVueComponent(filePath, {
  569. http = {}, uni = {}, wx = {}, apiRules = rules, timers = {}
  570. } = {}) {
  571. const context = vm.createContext({
  572. uni,
  573. wx,
  574. Date,
  575. Promise,
  576. String,
  577. Number,
  578. Boolean,
  579. Object,
  580. Array,
  581. setInterval: timers.setInterval || setInterval,
  582. clearInterval: timers.clearInterval || clearInterval,
  583. setTimeout: timers.setTimeout || setTimeout,
  584. clearTimeout: timers.clearTimeout || clearTimeout
  585. })
  586. const vueStub = new vm.SyntheticModule(['default'], function () {
  587. this.setExport('default', {})
  588. }, { context, identifier: 'test:vue-component' })
  589. const rulesStub = new vm.SyntheticModule(['default'], function () {
  590. this.setExport('default', apiRules)
  591. }, { context, identifier: 'test:team-background-rules' })
  592. const httpNames = [
  593. 'createTeamBackgroundSession',
  594. 'disableTeamBackgroundFile',
  595. 'downloadTeamBackgroundFile',
  596. 'listTeamBackgroundFiles',
  597. 'uploadTeamBackgroundFile'
  598. ]
  599. const httpStub = new vm.SyntheticModule(httpNames, function () {
  600. for (const name of httpNames) {
  601. this.setExport(name, http[name] || (() => Promise.resolve()))
  602. }
  603. }, { context, identifier: 'test:team-background-http' })
  604. const componentModule = new vm.SourceTextModule(readSfcScript(filePath), {
  605. context,
  606. identifier: pathToFileURL(filePath).href
  607. })
  608. await componentModule.link(specifier => {
  609. if (specifier === '@/http/teamBackgroundFile.js') return httpStub
  610. if (specifier === '@/utils/teamBackgroundFile.js') return rulesStub
  611. if (specifier.endsWith('.vue')) return vueStub
  612. throw new Error(`unexpected component import: ${specifier}`)
  613. })
  614. await componentModule.evaluate()
  615. return componentModule.namespace.default
  616. }
  617. function instantiateComponent(component, overrides = {}) {
  618. const base = Object.assign({ initialCount: 0 }, overrides)
  619. const data = typeof component.data === 'function' ? component.data.call(base) : {}
  620. const instance = Object.assign(base, data, overrides)
  621. for (const [name, method] of Object.entries(component.methods || {})) {
  622. instance[name] = method.bind(instance)
  623. }
  624. return instance
  625. }
  626. function createDeferred() {
  627. let resolve
  628. let reject
  629. const promise = new Promise((resolvePromise, rejectPromise) => {
  630. resolve = resolvePromise
  631. reject = rejectPromise
  632. })
  633. return { promise, resolve, reject }
  634. }
  635. function createFakeTimers() {
  636. let nextId = 1
  637. const pending = new Map()
  638. return {
  639. setTimeout(callback) {
  640. const id = nextId++
  641. pending.set(id, callback)
  642. return id
  643. },
  644. clearTimeout(id) {
  645. pending.delete(id)
  646. },
  647. count() {
  648. return pending.size
  649. },
  650. runNext() {
  651. const entry = pending.entries().next().value
  652. if (!entry) return false
  653. pending.delete(entry[0])
  654. entry[1]()
  655. return true
  656. },
  657. runAll() {
  658. while (this.runNext()) {}
  659. }
  660. }
  661. }
  662. async function flushPromises() {
  663. await Promise.resolve()
  664. await new Promise(resolve => setImmediate(resolve))
  665. }
  666. const backgroundComponentPath = path.join(__dirname, '../components/CusTeamBackgroundFiles/index.vue')
  667. const teamFillComponentPath = path.join(__dirname, '../components/CusTeamInfoFill/index.vue')
  668. const createTeamPagePath = path.join(__dirname, '../pagesPublish/fillTeamInfo.vue')
  669. const createListComponentPath = path.join(__dirname, '../pagesHome/components/createList.vue')
  670. const teamEditPagePath = path.join(__dirname, '../pagesMy/teamEdit.vue')
  671. const headerComponentPath = path.join(__dirname, '../components/CusHeader/index.vue')
  672. async function testDeferredPcSelectionSurvivesSessionFailure() {
  673. let createCalls = 0
  674. const firstRequest = createDeferred()
  675. const component = await loadVueComponent(backgroundComponentPath, {
  676. http: {
  677. createTeamBackgroundSession() {
  678. createCalls += 1
  679. if (createCalls === 1) return firstRequest.promise
  680. return Promise.resolve({
  681. code: '123456', uploadUrl: 'https://upload.example/retry', expiresAt: '2099-01-01 00:00:00'
  682. })
  683. }
  684. }
  685. })
  686. const instance = instantiateComponent(component, {
  687. teamId: '',
  688. editable: true,
  689. boundTeamId: 12,
  690. pcUploadDeferred: true,
  691. $showToast() {},
  692. $emit() {}
  693. })
  694. const first = instance.waitForDeferredPcUpload(12)
  695. const second = instance.waitForDeferredPcUpload(12)
  696. assert.equal(first, second, 'the whole deferred flow must expose one shared waiter')
  697. assert.equal(createCalls, 1)
  698. firstRequest.reject(new Error('session unavailable'))
  699. const failed = await Promise.allSettled([first, second])
  700. assert.deepEqual(failed.map(result => result.status), ['rejected', 'rejected'])
  701. assert.match(failed[0].reason.message, /session unavailable/)
  702. assert.equal(instance.pcUploadDeferred, true)
  703. assert.equal(instance.pcDialogVisible, false)
  704. assert.equal(instance.deferredPcResolve, null)
  705. assert.equal(instance.deferredPcWaitPromise, null)
  706. const retry = instance.waitForDeferredPcUpload(12)
  707. await flushPromises()
  708. assert.equal(createCalls, 2, 'a failed shared waiter must be retryable')
  709. assert.equal(typeof instance.deferredPcResolve, 'function')
  710. instance.skipDeferredPcUpload()
  711. await retry
  712. }
  713. async function testSessionRefreshFailureKeepsOldTimer() {
  714. const component = await loadVueComponent(backgroundComponentPath, {
  715. http: {
  716. createTeamBackgroundSession: () => Promise.reject(new Error('refresh failed'))
  717. }
  718. })
  719. const instance = instantiateComponent(component, {
  720. teamId: '', editable: true, boundTeamId: 12, $showToast() {}, $emit() {}
  721. })
  722. const oldSession = { code: '111111', expiresAt: '2099-01-01 00:00:00' }
  723. const oldTimer = setInterval(() => {}, 60 * 1000)
  724. instance.session = oldSession
  725. instance.sessionTimer = oldTimer
  726. try {
  727. await assert.rejects(instance.openPcSession(12), /refresh failed/)
  728. assert.equal(instance.session, oldSession)
  729. assert.equal(instance.sessionTimer, oldTimer)
  730. } finally {
  731. clearInterval(oldTimer)
  732. instance.sessionTimer = null
  733. }
  734. }
  735. async function testPcSessionCreationIsSingleFlightPerTeam() {
  736. const firstRequest = createDeferred()
  737. let createCalls = 0
  738. const component = await loadVueComponent(backgroundComponentPath, {
  739. http: {
  740. createTeamBackgroundSession() {
  741. createCalls += 1
  742. return firstRequest.promise
  743. }
  744. }
  745. })
  746. const instance = instantiateComponent(component, {
  747. teamId: '', editable: true, $showToast() {}, $emit() {}
  748. })
  749. instance.resetTeamContext(12)
  750. const first = instance.openPcSession(12)
  751. const second = instance.openPcSession(12)
  752. assert.equal(createCalls, 1, 'same-team callers must share one session POST')
  753. assert.equal(instance.sessionCreating, true)
  754. instance.refreshPcSession()
  755. assert.equal(createCalls, 1, 'disabled regenerate must not create another POST')
  756. instance.resetTeamContext(13)
  757. assert.equal(instance.sessionCreating, false, 'creating state follows the active team')
  758. firstRequest.resolve({
  759. code: '123456', uploadUrl: 'https://upload.example/', expiresAt: '2099-01-01 00:00:00'
  760. })
  761. assert.equal(await first, null)
  762. assert.equal(await second, null)
  763. assert.equal(instance.session, null, 'a stale context must not display the resolved session')
  764. assert.equal(instance.pcDialogVisible, false)
  765. }
  766. async function testPcSessionSingleFlightSurvivesSameTeamReset() {
  767. const request = createDeferred()
  768. let createCalls = 0
  769. const component = await loadVueComponent(backgroundComponentPath, {
  770. http: {
  771. createTeamBackgroundSession() {
  772. createCalls += 1
  773. return request.promise
  774. }
  775. }
  776. })
  777. const instance = instantiateComponent(component, {
  778. teamId: '', editable: true, $showToast() {}, $emit() {}
  779. })
  780. instance.resetTeamContext(21)
  781. const staleCaller = instance.openPcSession(21)
  782. instance.resetTeamContext(21)
  783. assert.equal(instance.sessionCreating, true, 'same-team reset must retain the network lock')
  784. const currentCaller = instance.openPcSession(21)
  785. assert.equal(createCalls, 1, 'same-team reset must reuse the raw network promise')
  786. const rawSession = {
  787. code: '654321', uploadUrl: 'https://upload.example/current', expiresAt: '2099-01-01 00:00:00'
  788. }
  789. request.resolve(rawSession)
  790. assert.equal(await staleCaller, null)
  791. assert.equal(await currentCaller, rawSession)
  792. assert.equal(instance.session, rawSession)
  793. assert.equal(instance.pcDialogVisible, true)
  794. assert.equal(instance.sessionCreating, false)
  795. instance.closePcDialog()
  796. }
  797. async function testPcSessionFailureClearsSingleFlightForRetry() {
  798. let createCalls = 0
  799. const component = await loadVueComponent(backgroundComponentPath, {
  800. http: {
  801. createTeamBackgroundSession() {
  802. createCalls += 1
  803. if (createCalls === 1) return Promise.reject(new Error('session unavailable'))
  804. return Promise.resolve({
  805. code: '222222', uploadUrl: 'https://upload.example/retry', expiresAt: '2099-01-01 00:00:00'
  806. })
  807. }
  808. }
  809. })
  810. const instance = instantiateComponent(component, {
  811. teamId: '', editable: true, $showToast() {}, $emit() {}
  812. })
  813. instance.resetTeamContext(22)
  814. await assert.rejects(instance.openPcSession(22), /session unavailable/)
  815. assert.equal(instance.sessionCreating, false)
  816. const session = await instance.openPcSession(22)
  817. assert.equal(createCalls, 2)
  818. assert.equal(session.code, '222222')
  819. assert.equal(instance.sessionCreating, false)
  820. instance.closePcDialog()
  821. }
  822. async function testDeferredPcFinishWaitsForListRefresh() {
  823. const component = await loadVueComponent(backgroundComponentPath, {
  824. http: {
  825. createTeamBackgroundSession: () => Promise.resolve({
  826. code: '123456',
  827. uploadUrl: 'https://upload.example/',
  828. expiresAt: '2099-01-01 00:00:00'
  829. }),
  830. listTeamBackgroundFiles: () => Promise.reject(new Error('list refresh failed'))
  831. }
  832. })
  833. const instance = instantiateComponent(component, {
  834. teamId: '', editable: true, boundTeamId: 12, pcUploadDeferred: true,
  835. $showToast() {}, $emit() {}
  836. })
  837. const waiting = instance.waitForDeferredPcUpload(12)
  838. await new Promise(resolve => setImmediate(resolve))
  839. assert.equal(typeof instance.deferredPcResolve, 'function')
  840. await instance.finishDeferredPcUpload()
  841. await assert.rejects(waiting, /list refresh failed/)
  842. }
  843. async function testDeferredPcWaiterSingleFlightFinishesAllCallers() {
  844. let createCalls = 0
  845. const sessionRequest = createDeferred()
  846. const component = await loadVueComponent(backgroundComponentPath, {
  847. http: {
  848. createTeamBackgroundSession() {
  849. createCalls += 1
  850. return sessionRequest.promise
  851. },
  852. listTeamBackgroundFiles: () => Promise.resolve([])
  853. }
  854. })
  855. const instance = instantiateComponent(component, {
  856. teamId: '', editable: true, boundTeamId: 12, pcUploadDeferred: true,
  857. $showToast() {}, $emit() {}
  858. })
  859. const first = instance.waitForDeferredPcUpload(12)
  860. const second = instance.waitForDeferredPcUpload(12)
  861. assert.equal(first, second)
  862. assert.equal(createCalls, 1)
  863. let settled = false
  864. first.then(() => { settled = true })
  865. sessionRequest.resolve({
  866. code: '654321', uploadUrl: 'https://upload.example/', expiresAt: '2099-01-01 00:00:00'
  867. })
  868. await flushPromises()
  869. assert.equal(settled, false, 'session creation must not settle the dialog waiter')
  870. await instance.finishDeferredPcUpload()
  871. await Promise.all([first, second])
  872. assert.equal(settled, true)
  873. assert.equal(instance.deferredPcWaitPromise, null)
  874. }
  875. async function testTeamContextResetAndUploadIsolation() {
  876. const uploads = []
  877. const component = await loadVueComponent(backgroundComponentPath, {
  878. http: {
  879. uploadTeamBackgroundFile(teamId, filePath, onProgress) {
  880. const deferred = createDeferred()
  881. uploads.push({ teamId, filePath, onProgress, deferred })
  882. return deferred.promise
  883. },
  884. listTeamBackgroundFiles: () => Promise.resolve([])
  885. }
  886. })
  887. let resolverCalls = 0
  888. const instance = instantiateComponent(component, {
  889. teamId: '',
  890. editable: true,
  891. $showToast() {},
  892. $emit() {}
  893. })
  894. instance.resetTeamContext(1)
  895. const oldItem = rules.createBackgroundQueueItem(
  896. { name: 'old.pdf', path: '/tmp/old.pdf', size: 1 }, 'old'
  897. )
  898. instance.queue.push(oldItem)
  899. instance.deferredPcResolve = () => { resolverCalls += 1 }
  900. const oldFlush = instance.flushPendingFiles(1)
  901. await new Promise(resolve => setImmediate(resolve))
  902. assert.equal(uploads.length, 1)
  903. instance.files = [{ id: 11, fileName: 'old.pdf' }]
  904. instance.count = 1
  905. instance.filesReady = true
  906. instance.session = { code: '111111' }
  907. instance.pcDialogVisible = true
  908. instance.textPreview = rules.createTextPreviewState({ fileName: 'old.txt', content: 'old' })
  909. instance.resetTeamContext(2)
  910. assert.equal(instance.boundTeamId, 2)
  911. assert.equal(instance.files.length, 0)
  912. assert.equal(instance.count, 0)
  913. assert.equal(instance.queue.length, 0)
  914. assert.equal(instance.filesReady, false)
  915. assert.equal(instance.session, null)
  916. assert.equal(instance.pcDialogVisible, false)
  917. assert.equal(instance.textPreview.content, '')
  918. assert.equal(resolverCalls, 1)
  919. const newItem = rules.createBackgroundQueueItem(
  920. { name: 'new.pdf', path: '/tmp/new.pdf', size: 1 }, 'new'
  921. )
  922. instance.queue.push(newItem)
  923. const newFlush = instance.flushPendingFiles(2)
  924. await new Promise(resolve => setImmediate(resolve))
  925. assert.equal(uploads.length, 2, 'the new team must not reuse the old upload promise')
  926. assert.deepEqual(uploads.map(item => item.teamId), [1, 2])
  927. uploads[0].onProgress(75)
  928. assert.equal(oldItem.progress, 0, 'stale upload progress must not mutate the old item after reset')
  929. uploads[0].deferred.resolve({ id: 101 })
  930. await oldFlush
  931. assert.equal(newItem.status, 'uploading')
  932. uploads[1].deferred.resolve({ id: 202 })
  933. await newFlush
  934. assert.equal(newItem.status, 'success')
  935. }
  936. async function testFileActionsWaitForCurrentListAndDocumentContext() {
  937. const listDeferred = createDeferred()
  938. const downloadDeferred = createDeferred()
  939. const opened = []
  940. const toasts = []
  941. let downloadCalls = 0
  942. const wx = {
  943. openDocument(options) {
  944. opened.push(options.filePath)
  945. setImmediate(() => options.success())
  946. }
  947. }
  948. const component = await loadVueComponent(backgroundComponentPath, {
  949. wx,
  950. http: {
  951. listTeamBackgroundFiles: () => listDeferred.promise,
  952. downloadTeamBackgroundFile: () => {
  953. downloadCalls += 1
  954. return downloadDeferred.promise
  955. }
  956. }
  957. })
  958. const instance = instantiateComponent(component, {
  959. teamId: '',
  960. editable: true,
  961. $showToast(message) { toasts.push(message) },
  962. $emit() {}
  963. })
  964. instance.resetTeamContext(3)
  965. const oldFile = { id: 31, fileName: 'old.pdf' }
  966. instance.files = [oldFile]
  967. instance.filesReady = true
  968. const refresh = instance.refreshFiles(3)
  969. await instance.previewFile(oldFile)
  970. assert.equal(downloadCalls, 0, 'old file ids must be disabled while the current list is loading')
  971. listDeferred.resolve([oldFile])
  972. await refresh
  973. const latePreview = instance.previewFile(oldFile)
  974. assert.equal(downloadCalls, 1)
  975. instance.resetTeamContext(4)
  976. downloadDeferred.resolve({ mode: 'document', fileName: 'old.pdf', filePath: '/tmp/old.pdf' })
  977. await latePreview
  978. assert.deepEqual(opened, [], 'a stale download must not open a native document')
  979. const validComponent = await loadVueComponent(backgroundComponentPath, {
  980. wx,
  981. http: {
  982. downloadTeamBackgroundFile: () => Promise.resolve({
  983. mode: 'document', fileName: 'current.pdf', filePath: '/tmp/current.pdf'
  984. })
  985. }
  986. })
  987. const validInstance = instantiateComponent(validComponent, {
  988. teamId: '', editable: true, $showToast(message) { toasts.push(message) }, $emit() {}
  989. })
  990. validInstance.resetTeamContext(5)
  991. const currentFile = { id: 51, fileName: 'current.pdf' }
  992. validInstance.files = [currentFile]
  993. validInstance.filesReady = true
  994. await validInstance.previewFile(currentFile)
  995. assert.deepEqual(opened, ['/tmp/current.pdf'])
  996. const failingComponent = await loadVueComponent(backgroundComponentPath, {
  997. wx: {
  998. openDocument(options) { setImmediate(() => options.fail(new Error('open failed'))) }
  999. },
  1000. http: {
  1001. downloadTeamBackgroundFile: () => Promise.resolve({
  1002. mode: 'document', fileName: 'broken.pdf', filePath: '/tmp/broken.pdf'
  1003. })
  1004. }
  1005. })
  1006. const failingInstance = instantiateComponent(failingComponent, {
  1007. teamId: '', editable: true, $showToast(message) { toasts.push(message) }, $emit() {}
  1008. })
  1009. failingInstance.resetTeamContext(6)
  1010. const brokenFile = { id: 61, fileName: 'broken.pdf' }
  1011. failingInstance.files = [brokenFile]
  1012. failingInstance.filesReady = true
  1013. await failingInstance.previewFile(brokenFile)
  1014. assert.ok(toasts.some(message => String(message).includes('open failed')))
  1015. }
  1016. async function testUploadedFileUsesDeleteWordingAndRefreshesAfterDelete() {
  1017. let modalOptions
  1018. const disableCalls = []
  1019. const toasts = []
  1020. const component = await loadVueComponent(backgroundComponentPath, {
  1021. uni: {
  1022. showModal(options) {
  1023. modalOptions = options
  1024. }
  1025. },
  1026. http: {
  1027. disableTeamBackgroundFile(teamId, fileId) {
  1028. disableCalls.push([teamId, fileId])
  1029. return Promise.resolve(true)
  1030. },
  1031. listTeamBackgroundFiles() {
  1032. return Promise.resolve([])
  1033. }
  1034. }
  1035. })
  1036. const instance = instantiateComponent(component, {
  1037. teamId: '',
  1038. editable: true,
  1039. $showToast(message) { toasts.push(message) },
  1040. $emit() {}
  1041. })
  1042. instance.resetTeamContext(5)
  1043. const file = { id: 51, fileName: '背景资料.pdf' }
  1044. instance.files = [file]
  1045. instance.filesReady = true
  1046. instance.removeFile(file)
  1047. assert.equal(modalOptions.title, '删除资料')
  1048. assert.match(modalOptions.content, /确定删除/)
  1049. modalOptions.success({ confirm: true })
  1050. await flushPromises()
  1051. assert.deepEqual(disableCalls, [[5, 51]])
  1052. assert.deepEqual(instance.files, [])
  1053. assert.ok(toasts.includes('已删除'))
  1054. const source = fs.readFileSync(backgroundComponentPath, 'utf8')
  1055. assert.match(source, />删除<\/view>/)
  1056. assert.doesNotMatch(source, /停用资料|已停用|停用失败/)
  1057. }
  1058. async function testSameTeamRefreshFailurePreservesExistingFilesAndCount() {
  1059. const listRequest = createDeferred()
  1060. const emittedCounts = []
  1061. const component = await loadVueComponent(backgroundComponentPath, {
  1062. http: { listTeamBackgroundFiles: () => listRequest.promise }
  1063. })
  1064. const instance = instantiateComponent(component, {
  1065. teamId: '', editable: true, $showToast() {},
  1066. $emit(name, value) { if (name === 'countChange') emittedCounts.push(value) }
  1067. })
  1068. instance.resetTeamContext(30)
  1069. const existingFiles = [{ id: 301, fileName: 'existing.pdf' }]
  1070. instance.files = existingFiles
  1071. instance.count = 1
  1072. instance.filesReady = true
  1073. instance.hasLoadedFiles = true
  1074. emittedCounts.length = 0
  1075. const refresh = instance.refreshFiles(30)
  1076. assert.equal(instance.files, existingFiles, 'same-team refresh must retain the visible list while loading')
  1077. assert.equal(instance.count, 1)
  1078. assert.deepEqual(emittedCounts, [], 'same-team refresh must not transiently emit zero')
  1079. listRequest.reject(new Error('refresh failed'))
  1080. await assert.rejects(refresh, /refresh failed/)
  1081. assert.equal(instance.files, existingFiles)
  1082. assert.equal(instance.count, 1)
  1083. assert.deepEqual(emittedCounts, [])
  1084. instance.resetTeamContext(31)
  1085. assert.equal(instance.files.length, 0)
  1086. assert.equal(instance.count, 0)
  1087. assert.deepEqual(emittedCounts, [0], 'switching teams must still clear the old count immediately')
  1088. }
  1089. async function testTeamWebsiteInputExposesTheAuthoritativeLengthLimit() {
  1090. const source = fs.readFileSync(teamFillComponentPath, 'utf8')
  1091. assert.match(source, /v-model="teamInfo\.enterpriseWebsite"[^>]*maxlength="500"/)
  1092. }
  1093. async function testTeamFillRendersBackgroundFilesAndBusyState() {
  1094. const source = fs.readFileSync(teamFillComponentPath, 'utf8')
  1095. assert.match(
  1096. source,
  1097. /<cus-team-background-files[^>]*ref="backgroundRef"[^>]*>/,
  1098. 'the team form must render the registered background-file component'
  1099. )
  1100. assert.match(
  1101. source,
  1102. /:class="\{ disabled: confirming \|\| submitting \}"/,
  1103. 'the submit button must expose its busy state'
  1104. )
  1105. const component = await loadVueComponent(teamFillComponentPath)
  1106. const state = component.data()
  1107. assert.equal(state.confirming, false, 'the submit lock must be reactive from initialization')
  1108. assert.equal(component.props.confirmText.type, String)
  1109. assert.equal(component.props.qtype.type, Boolean)
  1110. }
  1111. async function testTeamFillFlushesBeforeEmitAndLocks() {
  1112. const component = await loadVueComponent(teamFillComponentPath)
  1113. const flushDeferred = createDeferred()
  1114. let flushCalls = 0
  1115. let emitCalls = 0
  1116. const instance = instantiateComponent(component, {
  1117. teamId: 12,
  1118. qtype: false,
  1119. $props: { qtype: false },
  1120. $showToast() {},
  1121. $emit() { emitCalls += 1 },
  1122. $refs: {
  1123. backgroundRef: {
  1124. flushPendingFiles() { flushCalls += 1; return flushDeferred.promise },
  1125. hasUnresolvedFiles() { return false }
  1126. }
  1127. }
  1128. })
  1129. instance.teamInfo = {
  1130. teamName: '团队', enterpriseName: '公司', enterpriseWebsite: '无',
  1131. districtId: 1, industryId: 2, functionIds: [], orgIds: []
  1132. }
  1133. const first = instance.handleConfirm()
  1134. const second = instance.handleConfirm()
  1135. assert.equal(flushCalls, 1)
  1136. assert.equal(emitCalls, 0)
  1137. flushDeferred.resolve({ success: 1, failed: 0 })
  1138. await Promise.all([first, second])
  1139. assert.equal(emitCalls, 1)
  1140. }
  1141. async function testCreatedTeamResumeAndSubmitLock() {
  1142. const component = await loadVueComponent(createTeamPagePath)
  1143. let teamPostCalls = 0
  1144. let flushCalls = 0
  1145. const toasts = []
  1146. const instance = instantiateComponent(component, {
  1147. $api: {
  1148. post(url) {
  1149. assert.equal(url, '/core/user/team')
  1150. teamPostCalls += 1
  1151. return Promise.resolve({ data: { code: 0, data: { teamId: 88 } } })
  1152. }
  1153. },
  1154. $showToast(message) { toasts.push(message) },
  1155. $showModal: () => Promise.resolve(),
  1156. $refs: {
  1157. teamRef: {
  1158. flushBackgroundFiles() {
  1159. flushCalls += 1
  1160. if (flushCalls === 1) return Promise.reject(new Error('列表刷新失败'))
  1161. return Promise.resolve({ success: 0, failed: 0 })
  1162. },
  1163. hasUnresolvedBackgroundFiles: () => false,
  1164. hasDeferredPcUpload: () => false
  1165. }
  1166. }
  1167. })
  1168. let continuations = 0
  1169. instance.continueAfterTeamCreated = async teamId => {
  1170. assert.equal(teamId, 88)
  1171. continuations += 1
  1172. }
  1173. await instance.handleConfirm({ teamName: '团队' })
  1174. assert.equal(teamPostCalls, 1)
  1175. assert.equal(instance.creationState.createdTeamId, 88)
  1176. assert.ok(toasts.some(message => String(message).includes('背景资料')))
  1177. await instance.handleConfirm({ teamName: '团队' })
  1178. assert.equal(teamPostCalls, 1, 'retry after a later-stage failure must not POST a second team')
  1179. assert.equal(continuations, 1)
  1180. const lockedPost = createDeferred()
  1181. const lockedInstance = instantiateComponent(component, {
  1182. $api: { post: () => { teamPostCalls += 1; return lockedPost.promise } },
  1183. $showToast() {},
  1184. $showModal: () => Promise.resolve(),
  1185. $refs: { teamRef: {} }
  1186. })
  1187. const lockedFirst = lockedInstance.handleConfirm({ teamName: '团队' })
  1188. const callsAfterFirst = teamPostCalls
  1189. const lockedSecond = lockedInstance.handleConfirm({ teamName: '团队' })
  1190. assert.equal(teamPostCalls, callsAfterFirst, 'concurrent submission must be ignored')
  1191. lockedPost.resolve({ data: { code: 1, msg: '保存接口失败' } })
  1192. await Promise.all([lockedFirst, lockedSecond])
  1193. }
  1194. async function testCreatedTeamNavigationIsAwaitableAndResumable() {
  1195. const timers = createFakeTimers()
  1196. let navigationOptions
  1197. let teamPostCalls = 0
  1198. let publishCalls = 0
  1199. let teamPutCalls = 0
  1200. let flushCalls = 0
  1201. const toasts = []
  1202. const uni = {
  1203. getStorageSync(key) {
  1204. assert.equal(key, 'userInfo')
  1205. return JSON.stringify({ id: 7 })
  1206. },
  1207. removeStorageSync() {},
  1208. navigateTo(options) { navigationOptions = options }
  1209. }
  1210. const component = await loadVueComponent(createTeamPagePath, { uni, timers })
  1211. const originalFormat = Date.prototype.Format
  1212. Date.prototype.Format = () => '2026-07-21 12:00:00'
  1213. try {
  1214. const instance = instantiateComponent(component, {
  1215. next: '1', questionnaireId: 66, type: 'survey', title: '问卷',
  1216. $api: {
  1217. post(url, payload) {
  1218. if (url === '/core/user/team') {
  1219. teamPostCalls += 1
  1220. assert.equal(payload.enterpriseWebsite, 'https://old.example')
  1221. return Promise.resolve({ data: { code: 0, data: { teamId: 88 } } })
  1222. }
  1223. assert.equal(url, '/core/team/questionnaire/publish')
  1224. assert.deepEqual(Object.keys(payload).sort(), [
  1225. 'answerSetting', 'coachId', 'endTime', 'questionnaireId',
  1226. 'startTime', 'teamId', 'type'
  1227. ].sort())
  1228. publishCalls += 1
  1229. return Promise.resolve({ data: { code: 0, data: 321 } })
  1230. },
  1231. put(url, payload) {
  1232. teamPutCalls += 1
  1233. assert.equal(url, '/core/user/team')
  1234. assert.equal(payload.id, 88)
  1235. assert.equal(payload.enterpriseWebsite, 'https://new.example')
  1236. if (teamPutCalls === 1) {
  1237. return Promise.resolve({ data: { code: 9, msg: '官网更新失败' } })
  1238. }
  1239. return Promise.resolve({ data: { code: 0, data: true } })
  1240. }
  1241. },
  1242. $showToast(message) { toasts.push(message) },
  1243. $showModal: () => Promise.resolve(),
  1244. $refs: {
  1245. teamRef: {
  1246. flushBackgroundFiles() { flushCalls += 1; return Promise.resolve({ success: 0, failed: 0 }) },
  1247. hasUnresolvedBackgroundFiles: () => false,
  1248. hasDeferredPcUpload: () => false
  1249. }
  1250. }
  1251. })
  1252. const first = instance.handleConfirm({
  1253. teamName: '团队', enterpriseWebsite: 'https://old.example'
  1254. })
  1255. await flushPromises()
  1256. assert.equal(teamPostCalls, 1)
  1257. assert.equal(publishCalls, 1)
  1258. assert.equal(flushCalls, 1)
  1259. assert.equal(instance.creationState.teamQuestionnaireId, 321)
  1260. assert.equal(instance.creationState.completed, false)
  1261. assert.equal(instance.creationState.submitting, true)
  1262. assert.equal(timers.count(), 1)
  1263. timers.runNext()
  1264. await flushPromises()
  1265. assert.ok(navigationOptions)
  1266. assert.equal(instance.creationState.completed, false, 'navigation callback must settle first')
  1267. navigationOptions.fail({ errMsg: 'navigateTo:fail route missing' })
  1268. await first
  1269. assert.equal(instance.creationState.completed, false)
  1270. assert.equal(instance.creationState.submitting, false)
  1271. assert.equal(instance.creationState.stage, 'navigate')
  1272. assert.ok(toasts.some(message => String(message).includes('页面跳转失败')))
  1273. navigationOptions = null
  1274. const failedUpdate = instance.handleConfirm({
  1275. teamName: '团队', enterpriseWebsite: 'https://new.example'
  1276. })
  1277. await failedUpdate
  1278. assert.equal(teamPostCalls, 1)
  1279. assert.equal(publishCalls, 1)
  1280. assert.equal(flushCalls, 1)
  1281. assert.equal(teamPutCalls, 1)
  1282. assert.equal(instance.creationState.stage, 'update')
  1283. assert.ok(toasts.some(message => String(message).includes('团队更新失败:官网更新失败')))
  1284. assert.equal(timers.count(), 0)
  1285. const retry = instance.handleConfirm({
  1286. teamName: '团队', enterpriseWebsite: 'https://new.example'
  1287. })
  1288. await flushPromises()
  1289. assert.equal(teamPostCalls, 1, 'retry must reuse the created team id')
  1290. assert.equal(publishCalls, 1, 'retry after publish success must not publish again')
  1291. assert.equal(flushCalls, 1, 'navigate-stage retry must not repeat file processing')
  1292. assert.equal(teamPutCalls, 2, 'changed sanitized payload must update the same team')
  1293. assert.equal(timers.count(), 1)
  1294. timers.runNext()
  1295. await flushPromises()
  1296. assert.ok(navigationOptions)
  1297. assert.equal(instance.creationState.completed, false)
  1298. navigationOptions.success({})
  1299. await retry
  1300. assert.equal(instance.creationState.completed, true)
  1301. assert.equal(instance.creationState.submitting, false)
  1302. } finally {
  1303. if (originalFormat) Date.prototype.Format = originalFormat
  1304. else delete Date.prototype.Format
  1305. }
  1306. }
  1307. async function testCreatedTeamUnloadCancelsLateNavigation() {
  1308. const timers = createFakeTimers()
  1309. let navigateBackCalls = 0
  1310. const uni = {
  1311. navigateBack() { navigateBackCalls += 1 }
  1312. }
  1313. const component = await loadVueComponent(createTeamPagePath, { uni, timers })
  1314. const instance = instantiateComponent(component, {
  1315. $api: {
  1316. post: () => Promise.resolve({ data: { code: 0, data: { teamId: 89 } } })
  1317. },
  1318. $showToast() {},
  1319. $showModal: () => Promise.resolve(),
  1320. getOpenerEventChannel: () => ({ emit() {} }),
  1321. $refs: {
  1322. teamRef: {
  1323. flushBackgroundFiles: () => Promise.resolve({ success: 0, failed: 0 }),
  1324. hasUnresolvedBackgroundFiles: () => false,
  1325. hasDeferredPcUpload: () => false
  1326. }
  1327. }
  1328. })
  1329. const submission = instance.handleConfirm({ teamName: '团队', enterpriseWebsite: '无' })
  1330. await flushPromises()
  1331. assert.equal(timers.count(), 1)
  1332. component.onUnload.call(instance)
  1333. assert.equal(timers.count(), 0)
  1334. timers.runAll()
  1335. await submission
  1336. assert.equal(navigateBackCalls, 0)
  1337. assert.equal(instance.creationState.completed, false)
  1338. assert.equal(instance.creationState.submitting, false)
  1339. }
  1340. async function testTeamEditRedirectIsLockedAndResumable() {
  1341. const timers = createFakeTimers()
  1342. let redirectOptions
  1343. let putCalls = 0
  1344. let navigateBackCalls = 0
  1345. const toasts = []
  1346. const uni = {
  1347. redirectTo(options) { redirectOptions = options },
  1348. navigateBack() { navigateBackCalls += 1 }
  1349. }
  1350. const component = await loadVueComponent(teamEditPagePath, { uni, timers })
  1351. const instance = instantiateComponent(component, {
  1352. submitDto: { id: 12, teamName: '团队', enterpriseWebsite: 'https://old.example' },
  1353. show: true,
  1354. $api: {
  1355. put(url, payload) {
  1356. putCalls += 1
  1357. assert.equal(url, '/core/user/team')
  1358. assert.equal(payload.id, 12)
  1359. assert.equal(Object.hasOwn(payload, 'coachId'), false)
  1360. assert.equal(Object.hasOwn(payload, 'uploaderId'), false)
  1361. assert.equal(Object.hasOwn(payload, 'source'), false)
  1362. assert.equal(payload.enterpriseWebsite,
  1363. putCalls === 1 ? 'https://old.example' : 'https://new.example')
  1364. return Promise.resolve({ data: { code: 0, data: true } })
  1365. }
  1366. },
  1367. $showToast(message) { toasts.push(message) }
  1368. })
  1369. const first = instance.editConfirm()
  1370. await flushPromises()
  1371. assert.equal(putCalls, 1)
  1372. assert.equal(instance.saveSucceeded, true)
  1373. assert.equal(instance.saving, true, 'save lock must cover the redirect delay')
  1374. assert.equal(timers.count(), 1)
  1375. instance.editConfirm()
  1376. instance.requestBack()
  1377. assert.equal(putCalls, 1, 'confirm during redirect delay must not PUT again')
  1378. assert.equal(navigateBackCalls, 0, 'back during redirect delay must stay locked')
  1379. assert.ok(toasts.some(message => String(message).includes('正在保存')))
  1380. timers.runNext()
  1381. await flushPromises()
  1382. assert.ok(redirectOptions)
  1383. assert.equal(instance.saving, true, 'redirect callback must settle before unlock')
  1384. redirectOptions.fail({ errMsg: 'redirectTo:fail route missing' })
  1385. await first
  1386. assert.equal(instance.saving, false)
  1387. assert.equal(instance.saveSucceeded, true)
  1388. assert.equal(instance.saveStage, 'navigate')
  1389. redirectOptions = null
  1390. const retry = instance.editConfirm()
  1391. await flushPromises()
  1392. assert.equal(putCalls, 1, 'redirect retry must reuse the successful PUT')
  1393. assert.equal(instance.saving, true)
  1394. assert.equal(timers.count(), 1)
  1395. timers.runNext()
  1396. await flushPromises()
  1397. assert.ok(redirectOptions)
  1398. redirectOptions.fail({ errMsg: 'redirectTo:fail still missing' })
  1399. await retry
  1400. assert.equal(putCalls, 1)
  1401. redirectOptions = null
  1402. instance.handleConfirm({
  1403. id: 12,
  1404. teamName: '团队',
  1405. enterpriseWebsite: ' https://new.example ',
  1406. coachId: 7,
  1407. uploaderId: 8,
  1408. source: 'WECHAT'
  1409. })
  1410. const changedRetry = instance.editConfirm()
  1411. await flushPromises()
  1412. assert.equal(putCalls, 2, 'a changed payload must update the saved team before redirect')
  1413. assert.equal(instance.saving, true)
  1414. assert.equal(timers.count(), 1)
  1415. timers.runNext()
  1416. await flushPromises()
  1417. assert.ok(redirectOptions)
  1418. redirectOptions.success({})
  1419. await changedRetry
  1420. assert.equal(putCalls, 2)
  1421. assert.equal(instance.saving, false)
  1422. }
  1423. async function testTeamEditUnloadCancelsLateRedirect() {
  1424. const timers = createFakeTimers()
  1425. let redirectCalls = 0
  1426. const component = await loadVueComponent(teamEditPagePath, {
  1427. timers,
  1428. uni: { redirectTo() { redirectCalls += 1 } }
  1429. })
  1430. const instance = instantiateComponent(component, {
  1431. submitDto: { id: 12 },
  1432. $api: { put: () => Promise.resolve({ data: { code: 0, data: true } }) },
  1433. $showToast() {}
  1434. })
  1435. const saving = instance.editConfirm()
  1436. await flushPromises()
  1437. assert.equal(timers.count(), 1)
  1438. component.onUnload.call(instance)
  1439. assert.equal(timers.count(), 0)
  1440. timers.runAll()
  1441. await saving
  1442. assert.equal(redirectCalls, 0)
  1443. assert.equal(instance.saving, false)
  1444. }
  1445. async function testCloseAndBackRequirePendingUploadConfirmation() {
  1446. let modalOptions
  1447. let navigateBackCalls = 0
  1448. const uni = {
  1449. showModal(options) { modalOptions = options },
  1450. navigateBack() { navigateBackCalls += 1 }
  1451. }
  1452. const createList = await loadVueComponent(createListComponentPath, { uni })
  1453. const createListInstance = instantiateComponent(createList, {
  1454. $imgBase: 'https://image.example/',
  1455. teamInfoShow: true,
  1456. $refs: {
  1457. teamRef: {
  1458. hasUnresolvedBackgroundFiles: () => true,
  1459. isBackgroundUploadActive: () => false
  1460. }
  1461. }
  1462. })
  1463. createListInstance.requestCloseTeamInfo()
  1464. assert.equal(createListInstance.teamInfoShow, true)
  1465. modalOptions.success({ confirm: false })
  1466. assert.equal(createListInstance.teamInfoShow, true)
  1467. createListInstance.requestCloseTeamInfo()
  1468. modalOptions.success({ confirm: true })
  1469. assert.equal(createListInstance.teamInfoShow, false)
  1470. const teamEdit = await loadVueComponent(teamEditPagePath, { uni })
  1471. const teamEditInstance = instantiateComponent(teamEdit, {
  1472. $refs: {
  1473. teamRef: {
  1474. hasUnresolvedBackgroundFiles: () => true,
  1475. isBackgroundUploadActive: () => true
  1476. }
  1477. }
  1478. })
  1479. teamEditInstance.requestBack()
  1480. assert.equal(navigateBackCalls, 0)
  1481. modalOptions.success({ confirm: false })
  1482. assert.equal(navigateBackCalls, 0)
  1483. teamEditInstance.requestBack()
  1484. modalOptions.success({ confirm: true })
  1485. assert.equal(navigateBackCalls, 1)
  1486. let headerBackEvents = 0
  1487. const header = await loadVueComponent(headerComponentPath, { uni })
  1488. const headerInstance = instantiateComponent(header, {
  1489. interceptBack: true,
  1490. $emit(name) { if (name === 'back') headerBackEvents += 1 }
  1491. })
  1492. headerInstance.toBack('')
  1493. assert.equal(headerBackEvents, 1)
  1494. assert.equal(navigateBackCalls, 1, 'intercepted header back must not navigate directly')
  1495. }
  1496. async function main() {
  1497. const loadedTransport = await loadTransport()
  1498. assert.equal(typeof loadedTransport.downloadTeamBackgroundFile, 'function')
  1499. await testConcurrentSilentRequestDoesNotStrandLoadingMask()
  1500. await testUploadTransport()
  1501. await testApiTransport()
  1502. await testDownloadTransport()
  1503. await testDeferredPcSelectionSurvivesSessionFailure()
  1504. await testSessionRefreshFailureKeepsOldTimer()
  1505. await testPcSessionCreationIsSingleFlightPerTeam()
  1506. await testPcSessionSingleFlightSurvivesSameTeamReset()
  1507. await testPcSessionFailureClearsSingleFlightForRetry()
  1508. await testDeferredPcFinishWaitsForListRefresh()
  1509. await testDeferredPcWaiterSingleFlightFinishesAllCallers()
  1510. await testTeamContextResetAndUploadIsolation()
  1511. await testFileActionsWaitForCurrentListAndDocumentContext()
  1512. await testUploadedFileUsesDeleteWordingAndRefreshesAfterDelete()
  1513. await testSameTeamRefreshFailurePreservesExistingFilesAndCount()
  1514. await testTeamWebsiteInputExposesTheAuthoritativeLengthLimit()
  1515. await testTeamFillRendersBackgroundFilesAndBusyState()
  1516. await testTeamFillFlushesBeforeEmitAndLocks()
  1517. await testCreatedTeamResumeAndSubmitLock()
  1518. await testCreatedTeamNavigationIsAwaitableAndResumable()
  1519. await testCreatedTeamUnloadCancelsLateNavigation()
  1520. await testTeamEditRedirectIsLockedAndResumable()
  1521. await testTeamEditUnloadCancelsLateRedirect()
  1522. await testCloseAndBackRequirePendingUploadConfirmation()
  1523. console.log('team background transport: PASS')
  1524. console.log('team background component behavior: PASS')
  1525. }
  1526. main().catch(error => {
  1527. console.error(error)
  1528. process.exitCode = 1
  1529. })