超测返回不同的身体

发布于 2025-01-14 01:18:30 字数 4942 浏览 7 评论 0原文

我有一个 e2e 测试,我测试注册(电子邮件唯一)

测试是:

    it('Register a default user: /api/v1/auth/email/register (POST)', async () => {

        return request(app.getHttpServer())
          .post('/auth/email/register')
          .send({
            "name": newUserName,
            "username": newUsername,
            "email": TESTER_EMAIL,
            "password": TESTER_PASSWORD
          })
          .expect(201);
      });

第二次,使用相同的值,我期望 400 状态代码,我得到了它。

    it('Register a default user: /api/v1/auth/email/register (POST)', async () => {

        return request(app.getHttpServer())
          .post('/auth/email/register')
          .send({
            "name": newUserName,
            "username": newUsername,
            "email": TESTER_EMAIL,
            "password": TESTER_PASSWORD
          })
          .expect(400)
          .expect(({ body }) => {
            console.log(body);
          });
      });

如果我分析正文,我可以看到:

     {
          index: 0,
          code: 11000,
          keyPattern: { email: 1 },
          keyValue: { email: '[email protected]' }
        }

这是正确的,因为我的 mongoDB 上有一个唯一的索引。 但我期望从生产 API 中收到相同的响应。

{
  "statusCode": 400,
  "message": [
    "username already exist",
    "email already exist"
  ],
  "error": "Bad Request"
}

控制器很简单,我的路线如下:

      @Post('email/register')
      @HttpCode(HttpStatus.CREATED)
      async register(@Body() authRegisterLoginDto: AuthRegisterLoginDto) {
        return this.authService.register(authRegisterLoginDto);
      }

在我的服务中:

    async register(authRegisterLoginDto: AuthRegisterLoginDto) {
    
        const hash = crypto.createHash('sha256').update(randomStringGenerator()).digest('hex');
        const user = await this.usersService.create({
          ...authRegisterLoginDto,
          hash,
        });
    
        await this.mailService.userSignUp({
          to: user.email,
          data: {
            hash,
          },
        });
      }

在我的 userService 中(我收到错误)是:

    async create(userDto: UserDto): Promise<IUsers> {
        try {
          return await this.userModel.create(userDto);
        } catch (err) {      
          throw new HttpException(err, HttpStatus.BAD_REQUEST);
        }
      }

如何获得与从“prod”API 获得的相同响应?

更新。

main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe, VersioningType } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { TransformationInterceptor } from './interceptors/transformInterceptor';
import { TransformError } from './interceptors/transformErrorInterceptor';
import { useContainer } from 'class-validator';
import { ConfigService } from '@nestjs/config';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const configService = app.get(ConfigService);
  //added for custom validator
  useContainer(app.select(AppModule), {fallbackOnErrors: true});
  //custom response
  app.useGlobalInterceptors(new TransformationInterceptor)
  app.useGlobalInterceptors(new TransformError)  
  app.setGlobalPrefix(configService.get('app.apiPrefix'), {
    exclude: ['/'],
  });
  app.enableVersioning({
    type: VersioningType.URI,
  });
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      transform: true,
      forbidNonWhitelisted: true,
      transformOptions: {
        enableImplicitConversion: true,
      },
    }),
  );

  const config = new DocumentBuilder()
    .setTitle('API')
    .setDescription('The API description')
    .setVersion('1.0')
    .addBearerAuth(
      {
        type: 'http',
        scheme: 'bearer',
        bearerFormat: 'JWT',
        name: 'JWT',
        description: 'Enter JWT token',
        in: 'header',
      },
      'JWT-auth', // This name here is important for matching up with @ApiBearerAuth() in your controller!
    )
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api/doc', app, document);

  app.enableCors();
  await app.listen(configService.get('app.port'));

}
bootstrap();

jest-e2e.json

{
  "moduleFileExtensions": ["js", "json", "ts"],
  "rootDir": ".",
  "testEnvironment": "node",
  "testRegex": ".e2e-spec.ts$",
  "transform": {
    "^.+\\.(t|j)s$": "ts-jest"
  }
}

I have an e2e test where I test the registration (email unique)

The Test is:

    it('Register a default user: /api/v1/auth/email/register (POST)', async () => {

        return request(app.getHttpServer())
          .post('/auth/email/register')
          .send({
            "name": newUserName,
            "username": newUsername,
            "email": TESTER_EMAIL,
            "password": TESTER_PASSWORD
          })
          .expect(201);
      });

The second time, with the same values, I expect a 400 Status code, and I got it.

    it('Register a default user: /api/v1/auth/email/register (POST)', async () => {

        return request(app.getHttpServer())
          .post('/auth/email/register')
          .send({
            "name": newUserName,
            "username": newUsername,
            "email": TESTER_EMAIL,
            "password": TESTER_PASSWORD
          })
          .expect(400)
          .expect(({ body }) => {
            console.log(body);
          });
      });

If I analyze the Body, I can see:

     {
          index: 0,
          code: 11000,
          keyPattern: { email: 1 },
          keyValue: { email: '[email protected]' }
        }

and it is correct, Because I have an index unique on my mongoDB.
But I expect the same response that I receive from my production API.

{
  "statusCode": 400,
  "message": [
    "username already exist",
    "email already exist"
  ],
  "error": "Bad Request"
}

The controller is simple, I have a route like:

      @Post('email/register')
      @HttpCode(HttpStatus.CREATED)
      async register(@Body() authRegisterLoginDto: AuthRegisterLoginDto) {
        return this.authService.register(authRegisterLoginDto);
      }

In my service:

    async register(authRegisterLoginDto: AuthRegisterLoginDto) {
    
        const hash = crypto.createHash('sha256').update(randomStringGenerator()).digest('hex');
        const user = await this.usersService.create({
          ...authRegisterLoginDto,
          hash,
        });
    
        await this.mailService.userSignUp({
          to: user.email,
          data: {
            hash,
          },
        });
      }

and in my userService(wehre I get the error) is:

    async create(userDto: UserDto): Promise<IUsers> {
        try {
          return await this.userModel.create(userDto);
        } catch (err) {      
          throw new HttpException(err, HttpStatus.BAD_REQUEST);
        }
      }

How can I get the same response that I get from my "prod" API?

UPDATE.

main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe, VersioningType } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { TransformationInterceptor } from './interceptors/transformInterceptor';
import { TransformError } from './interceptors/transformErrorInterceptor';
import { useContainer } from 'class-validator';
import { ConfigService } from '@nestjs/config';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const configService = app.get(ConfigService);
  //added for custom validator
  useContainer(app.select(AppModule), {fallbackOnErrors: true});
  //custom response
  app.useGlobalInterceptors(new TransformationInterceptor)
  app.useGlobalInterceptors(new TransformError)  
  app.setGlobalPrefix(configService.get('app.apiPrefix'), {
    exclude: ['/'],
  });
  app.enableVersioning({
    type: VersioningType.URI,
  });
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      transform: true,
      forbidNonWhitelisted: true,
      transformOptions: {
        enableImplicitConversion: true,
      },
    }),
  );

  const config = new DocumentBuilder()
    .setTitle('API')
    .setDescription('The API description')
    .setVersion('1.0')
    .addBearerAuth(
      {
        type: 'http',
        scheme: 'bearer',
        bearerFormat: 'JWT',
        name: 'JWT',
        description: 'Enter JWT token',
        in: 'header',
      },
      'JWT-auth', // This name here is important for matching up with @ApiBearerAuth() in your controller!
    )
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api/doc', app, document);

  app.enableCors();
  await app.listen(configService.get('app.port'));

}
bootstrap();

jest-e2e.json

{
  "moduleFileExtensions": ["js", "json", "ts"],
  "rootDir": ".",
  "testEnvironment": "node",
  "testRegex": ".e2e-spec.ts
quot;,
  "transform": {
    "^.+\\.(t|j)s
quot;: "ts-jest"
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

裸钻 2025-01-21 01:18:30

我不知道您的 E2E 测试如何引导应用程序,但请确保包含所有转换管道以及可能涉及更改错误响应的所有其他内容。

为了在 e2e 测试中获得相同的效果,请始终包含 main.ts 中的设置,除了 swagger 文档或一些不相关的内容。

对于你的情况,我会尝试这个

let app: INestApplication;

beforeEach(async () => {

  const moduleFixture: TestingModule = await Test.createTestingModule({
    imports: [AppModule],
  }).compile();

  app = moduleFixture.createNestApplication();
  app.useGlobalInterceptors(new TransformationInterceptor);
  app.useGlobalInterceptors(new TransformError);

  await app.init();
});

I don't see how your E2E test bootstraps the app but make sure all transformation pipes are included and everything else that might be involved altering error response.

To get the same effect in the e2e test always include the setup you have in main.ts except swagger docs or some unrelated stuff.

in your case, I'd try this

let app: INestApplication;

beforeEach(async () => {

  const moduleFixture: TestingModule = await Test.createTestingModule({
    imports: [AppModule],
  }).compile();

  app = moduleFixture.createNestApplication();
  app.useGlobalInterceptors(new TransformationInterceptor);
  app.useGlobalInterceptors(new TransformError);

  await app.init();
});
我家小可爱 2025-01-21 01:18:30

感谢@n1md7,我导入了
useContainer(app.select(AppModule), {fallbackOnErrors: true });

进入我的 e2e 测试。我修改了它,因为我想

  @Validate(UniqueValidator, ['username'], {
    message: 'username already exist',
  })

在我的 Dto 中使用它。 (MongoDB 和类验证器唯一验证 - NESTJS

Thanks to @n1md7, I imported
useContainer(app.select(AppModule), { fallbackOnErrors: true });

into my e2e test. I modified it because I want to use the

  @Validate(UniqueValidator, ['username'], {
    message: 'username already exist',
  })

in my Dto. (MongoDB and class-validator unique validation - NESTJS)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文