Purpose:
Test controller method with file stream response.
Controller:
@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);
}
Test unit:
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');
});
});
CodePudding user response:
- Create stream from any data
- expect a buffer as response body
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);
});
});