While e2e testing with jest/supertest the body returned from my app seems to be a buffer rather than just JSON.
The test module:
const testingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
const app = testingModule.createNestApplication();
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
}),
);
await app.init();
server = app.getHttpServer();
In the test I expect the ValidationPipe
to throw an error about the password being too short:
const res = request(server)
.post(path)
.accept('application/json')
.responseType('application/json')
.set('Authorization', `Bearer ${token}`)
.send({
email: 'abc@abc.abc',
displayName: 'Abc',
password: 'abc'
});
res.expect({error: 'Bad Request'}); // fails with expected { error: 'Bad Request' } response body, got <Buffer 7b 22 73 74...
The endpoint is:
@Post()
@UseGuards(AnonymousGuard)
@ApiBearerAuth('Firebase JWT')
@ApiCreatedResponse({ description: 'Success' })
@ApiUnauthorizedResponse({ description: 'Authorization failed' })
@ApiConflictResponse({ description: 'User exists' })
@ApiBadRequestResponse({ description: 'Malformed request' })
createUser(@Body() body: CreateUserBody) {
throw new HttpException('not implemented', HttpStatus.NOT_IMPLEMENTED);
}
And the validation in:
export class CreateUserBody {
@IsEmail()
@ApiProperty()
email: string;
@IsString()
@MinLength(2)
@MaxLength(30)
@ApiProperty()
displayName: string;
@IsString()
@MinLength(8)
@ApiProperty()
password: string;
}
The problem is that the test response doesn't contain JSON but rather a buffer:
console.log(res.body); // <Buffer 7b 22 73 74 61 74 75...
console.log(JSON.parse(res.body)); // { error: "Bad request",
message: [ 'password must be longer...
I do not use any interceptors but some middleware I've got is async – could this be a problem?
I can get away with parsing the body, but every example on the internet seems to just use req.body
(e.g. https://docs.nestjs.com/fundamentals/testing#end-to-end-testing) while I can't seem to be able to and I'm not sure what could cause that.
Removing .responseType('application/json')
that I had copied from some website seems to have solved it. That converts the response into a Buffer.