【问题标题】:Nestjs how to mock file download in testNestjs如何在测试中模拟文件下载
【发布时间】:2022-01-26 09:08:53
【问题描述】:

目的:

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

控制器:

@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');
    });
});

【问题讨论】:

    标签: unit-testing jestjs nestjs


    【解决方案1】:
    • 从任何数据创建流
    • 期望缓冲区作为响应正文
    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);
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-22
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      相关资源
      最近更新 更多