【问题标题】:NestJS E2E tests with Jest. Injected service returns undefined (only tests)NestJS 使用 Jest 进行 E2E 测试。注入的服务返回未定义(仅测试)
【发布时间】:2021-07-15 02:35:28
【问题描述】:

我的用户模块的端到端测试有问题。当用户在 /users 中发出 GET 请求并在查询参数中发送此代码时,我想验证是否存在“companyCode”。如果此公司代码存在,此验证器将搜索数据库,如果不存在则返回错误。问题是在测试中这个验证不会发生,因为“companiesService”返回未定义(仅在测试中),缺少什么?

可能的解决方案:与 useContainer(class-validator) 相关的问题。

谢谢。


users.e2e-spec.ts

describe('UsersController (e2e)', () => {
  let app: INestApplication;
  let repository: Repository<User>;

  beforeAll(async () => {
    const module = await Test.createTestingModule({
      imports: [UsersModule, AuthModule, TypeOrmModule.forRoot(ormConfig)],
      providers: [
        {
          provide: APP_GUARD,
          useClass: AuthGuard,
        },
      ],
    }).compile();

    app = module.createNestApplication();
    app.useGlobalPipes(new ValidationPipe());
    useContainer(app.select(UsersModule), { fallbackOnErrors: true });

    repository = module.get('UserRepository');
    await app.init();
  });

  afterAll(async () => {
    await app.close();
  });

  describe('/users (GET)', () => {
    it('should return users if requesting user sent "companyCode" in the request body', async (done) => {
      return request(app.getHttpServer())
        .get('/users')
        .auth('admin', 'admin')
        .query({ companyCode: '2322661870558778503' }) // should return 200 because companyCode exists but is returning 400
        .expect(200)
        .then((res) => {
          expect(res.body.users).toHaveLength(1);
          done();
        })
        .catch((err) => done(err));
    });
  });
});

users.module.ts

@Module({
  controllers: [UsersController],
  providers: [UsersService, UserExistsRule],
  imports: [
    TypeOrmModule.forFeature([
      User,
      Person,
      Type,
      Profile,
      UserProfile,
      Company,
    ]),
    CompaniesModule,
  ],
  exports: [UsersService],
})
export class UsersModule {}

read-users.dto.ts

export class ReadUsersDto {
  @IsOptional()
  @IsNotEmpty()
  @IsString()
  @MinLength(1)
  @MaxLength(255)
  public name?: string;

  @IsOptional()
  @IsNotEmpty()
  @IsNumberString()
  @Type(() => String)
  @Validate(CompanyExistsRule)
  public companyCode?: string;
}

companies.module.ts

@Module({
  providers: [CompaniesService, CompanyExistsRule],
  imports: [TypeOrmModule.forFeature([Company, Person])],
  exports: [CompaniesService],
})
export class CompaniesModule {}

companies.decorator.ts

@ValidatorConstraint({ name: 'CompanyExists', async: true })
@Injectable()
export class CompanyExistsRule implements ValidatorConstraintInterface {
  constructor(private companiesService: CompaniesService) {}

  async validate(code: string) {
    try {
      console.log('companiesService', this.companiesService); // returns undefined on test
      await this.companiesService.findOneByCode(code);
    } catch (e) {
      return false;
    }

    return true;
  }

  defaultMessage() {
    return `companyCode doesn't exist`;
  }
}

【问题讨论】:

    标签: dependency-injection jestjs nestjs e2e-testing class-validator


    【解决方案1】:

    我发现我是从 typeorm 导入 useContainer 而不是 class-validator haha​​hahha。

    // incorrectly imported
    import { useContainer } from 'typeorm';  
    
    // correctly imported
    import { useContainer } from 'class-validator';
    

    【讨论】:

      猜你喜欢
      • 2020-11-16
      • 2019-08-29
      • 2019-04-19
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 2021-05-17
      • 2020-05-15
      • 2018-08-29
      相关资源
      最近更新 更多