/** @jest-environment node */ import archiver from 'archiver' import { Readable } from 'node:stream' import { createArchiveDownloadStream } from '@/lib/archive-download-stream' class OpenReadable extends Readable { private emitted = false override _read(): void { if (!this.emitted) { this.emitted = true this.push(Buffer.alloc(64 * 1024, 1)) } } } describe('createArchiveDownloadStream', () => { test('取消动态 ZIP 时应中止 Archiver 并销毁显式输入流', async () => { const archive = archiver('zip', { zlib: { level: 1 } }) const abortSpy = jest.spyOn(archive, 'abort') const source = new OpenReadable() const sourceDestroySpy = jest.spyOn(source, 'destroy') const download = createArchiveDownloadStream(archive) archive.append(download.trackSource(source), { name: 'open.bin' }) const reader = download.finalize().getReader() await reader.read() await reader.cancel() expect(abortSpy).toHaveBeenCalledTimes(1) expect(sourceDestroySpy).toHaveBeenCalled() expect(source.destroyed).toBe(true) expect(archive.destroyed).toBe(true) expect((archive as any)._state?.aborted).toBe(true) expect((archive as any)._queue?.length?.() || 0).toBe(0) }) })