Open
Description
This code:
import { IsNotEmpty, IsOptional, IsString, validate } from 'class-validator';
import { plainToClass } from 'class-transformer';
const PATCH = 'patch';
const POST = 'post';
export class Test {
@IsOptional({ groups: [PATCH] })
@IsNotEmpty({ always: true })
@IsString()
name: string;
}
async function getValidationErrors(obj, group) {
return await validate(plainToClass(Test, obj), { groups: [group] });
}
describe('Test', () => {
it('should fail on post without name', async () => {
const errors = await getValidationErrors({}, POST);
expect(errors).not.toEqual([]);
});
it('should fail on post when name is undefined', async () => {
const errors = await getValidationErrors({ name: undefined }, POST);
expect(errors).not.toEqual([]);
});
it('should fail on post when name is null', async () => {
const errors = await getValidationErrors({ name: null }, POST);
expect(errors).not.toEqual([]);
});
it('should fail on post when name is empty', async () => {
const errors = await getValidationErrors({ name: '' }, POST);
expect(errors).not.toEqual([]);
});
it('should succeed on patch without name property', async () => {
const errors = await getValidationErrors({}, PATCH);
expect(errors).toEqual([]);
});
it('should fail on patch when name is undefined', async () => {
const errors = await getValidationErrors({ name: undefined }, PATCH);
expect(errors).not.toEqual([]);
});
it('should fail on patch when name is null', async () => {
const errors = await getValidationErrors({ name: null }, PATCH);
expect(errors).not.toEqual([]);
});
it('should fail on patch when name is empty', async () => {
const errors = await getValidationErrors({ name: '' }, PATCH);
expect(errors).not.toEqual([]);
});
});
gives the following results:
Am I missing something here?
Looking at the code of @IsOptional I see that it checks that the property is not undefined or null, that's why the test for empty string is not failing, but in theory shouldn't it check that this property exists on the object?