jeudi 4 mars 2021

Nestjs pipe works when I manually create entity but not in jest test

I have a validation pipe to check input that works when I manually create a product(using postman), but it doesn't check when I run tests. any explanations?

my validator:

@Injectable()
export class JoiValidationPipe implements PipeTransform {
  constructor(private schema: ObjectSchema) {}

  transform(value: any, metadata: ArgumentMetadata) {
    const { error } = this.schema.validate(value);
    if (error) {
      throw new HttpException('Validation failed', HttpStatus.BAD_REQUEST);
    }
    return value;
  }
}

my controller:

  @UsePipes(new JoiValidationPipe(productSchema))
  @Post()
  async create(@Body() createProductDto: CreateProductDto): Promise<Product> {
    return (await this.productsService.create(createProductDto)).product;
  }

my test:

beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [ProductsController],
      providers: [ProductsService],
    }).compile();

    controller = module.get<ProductsController>(ProductsController);
    service = module.get<ProductsService>(ProductsService);
  });    

describe('create()', () => {
        it('should fail to add a new product', async () => {
          const result: Product = {
            name: 'p',
            price: -100,
            category: 'junk',
          };
    
          expect(await controller.create(result)).toBe(result);
        });
      });

my schema:

export const productSchema: ObjectSchema = object({
  createProductDto: object().keys({
    name: string().min(5).required(),
    price: number().integer().min(0).default(0),
    category: string().min(5).required(),
  }),
});

Aucun commentaire:

Enregistrer un commentaire