Skip to content

Commit

Permalink
test(sample): add file upload e2e test
Browse files Browse the repository at this point in the history
add test using file parse pipe
  • Loading branch information
thiagomini committed Jun 17, 2022
1 parent ad0d1bc commit 2e8426b
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
23 changes: 22 additions & 1 deletion sample/29-file-upload/e2e/app/app.e2e-spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { readFileSync } from 'fs';
import { join } from 'path';
import * as request from 'supertest';
import { AppModule } from '../../src/app.module';

Expand Down Expand Up @@ -30,6 +29,28 @@ describe('E2E FileTest', () => {
});
});

it('should allow for file uploads that pass validation', async () => {
return request(app.getHttpServer())
.post('/file/pass-validation')
.attach('file', './package.json')
.field('name', 'test')
.expect(201)
.expect({
body: {
name: 'test',
},
file: readFileSync('./package.json').toString(),
});
});

it('should throw for file uploads that do not pass validation', async () => {
return request(app.getHttpServer())
.post('/file/fail-validation')
.attach('file', './package.json')
.field('name', 'test')
.expect(400);
});

afterAll(async () => {
await app.close();
});
Expand Down
39 changes: 39 additions & 0 deletions sample/29-file-upload/src/app.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
Body,
Controller,
Get,
ParseFilePipeBuilder,
Post,
UploadedFile,
UseInterceptors,
Expand Down Expand Up @@ -31,4 +32,42 @@ export class AppController {
file: file.buffer.toString(),
};
}

@UseInterceptors(FileInterceptor('file'))
@Post('file/pass-validation')
uploadFileAndPassValidation(
@Body() body: SampleDto,
@UploadedFile(
new ParseFilePipeBuilder()
.addFileTypeValidator({
fileType: 'json',
})
.build(),
)
file: Express.Multer.File,
) {
return {
body,
file: file.buffer.toString(),
};
}

@UseInterceptors(FileInterceptor('file'))
@Post('file/fail-validation')
uploadFileAndFailValidation(
@Body() body: SampleDto,
@UploadedFile(
new ParseFilePipeBuilder()
.addFileTypeValidator({
fileType: 'jpg',
})
.build(),
)
file: Express.Multer.File,
) {
return {
body,
file: file.buffer.toString(),
};
}
}

0 comments on commit 2e8426b

Please sign in to comment.