Nestjs如何在测试中模拟文件下载

Nestjs how to mock file download in test

目的:

使用文件流响应测试控制器方法。

控制器:

@Get('/resources/pdf/:fileId')
@HttpCode(HttpStatus.OK)
public async downloadPdf(
    @Param('fileId') fileId: string,
@Res() response: Response
): Promise<void> {
    const fileReadableStream = await myService.downloadPdf(fileId);
    response.setHeader('Content-Type', 'application/pdf');
    fileReadableStream.pipe(response);
}

测试单位:

describe('FileDownloadController', () => {
    it('should download file with specific header', async () => {
        await request(app.getHttpServer())
            .get('/resources/pdf/myFileId')
            .expect(200)
            .expect('Content-Type', 'application/pdf')
            .expect('my file content');
    });
});
  • 从任何数据创建流
  • 期望缓冲区作为响应主体
import { Buffer } from 'buffer';
import { Readable } from 'stream';

describe('FileDownloadController', () => {
    let myMockService: MockProxy<MyService> & MyService;

    it('should download file with specific header', async () => {
        const body = Buffer.from('my file content');
        const mockReadableStream = Readable.from(body);

        myMockService.downloadPdf.calledWith('myFileId').mockResolvedValue(mockReadableStream);

        await request(app.getHttpServer())
            .get('/resources/pdf/myFileId')
            .expect(200)
            .expect('Content-Type', 'application/pdf')
            .expect(body);
    });
});