I have a custom validation pipe in NestJS where I set skipMissingProperties to true, so when I don't send a field that is decorated with IsDefined the validation will not throw exception. For example, if the DTO is:
class ModelDTO {
@IsDefined()
@IsNumber()
requiredNumber1: number;
@IsDefined()
@IsNumber()
requiredNumber2: number;
}
and the actual object the validation pipe accepts is:
{
requiredNumber2: 1
}
it doesn't fail (I save some log in this case).
When I do e2e tests it works fine - I can see the validation pipe continues to the controller and that I get the desired log.
For some reason when I do unit-tests for some reason the same case failes with Bad Request (400) exception, the error message is requiredNumber2 should not be null or undefined.
Why the unit-test fails while the e2e works well? (By the way - in manual tests the pipe also works well).
EDIT: the pipe is:
class CustomValidationPipe extends ValidationPipe {
const OPTIONS = {
transform: true,
skipMissingProperties: true,
whitelist: true,
forbidNonWhitelisted: false,
forbidUnknownValues: true,
transformOptions: {
enableImplicitConversion: true,
}
}
constructor() {
super(OPTIONS);
}
async transform(value, metadata) {
const objectToValidate = plainToClass(
metadata.metatype,
cloneDeep(value)
);
const errors = await validate(
objectToValidate,
{
...OPTIONS,
skipMissingProperties: false,
forbidNonWhitelisted: true,
}
)
if (errors.length > 0) {
// log
}
return super.transform(value, metadata);
}
}