NestJS在e2e中返回缓冲区而不是JSON



当e2e使用jest/supertest进行测试时,从我的应用程序返回的主体似乎是一个缓冲区,而不仅仅是JSON。

测试模块:

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();

在测试中,我预计ValidationPipe会抛出一个关于密码太短的错误:

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...

终点是:

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

以及在中的验证

export class CreateUserBody {
@IsEmail()
@ApiProperty()
email: string;
@IsString()
@MinLength(2)
@MaxLength(30)
@ApiProperty()
displayName: string;
@IsString()
@MinLength(8)
@ApiProperty()
password: string;
}

问题是测试响应不包含JSON,而是包含一个缓冲区:

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...

我不使用任何拦截器,但我拥有的一些中间件是异步的——这会是个问题吗?

我可以解析正文,但互联网上的每个例子似乎都只使用req.body(例如。https://docs.nestjs.com/fundamentals/testing#end-结束测试(,而我似乎无法做到,我也不确定是什么原因造成的。

删除我从某个网站复制的.responseType('application/json')似乎已经解决了这个问题。这将响应转换为缓冲区。

最新更新