我正在使用打字稿进行 nodeJs 项目。在这里,我使用 class-validator 来验证输入并使用 jest 来运行单元测试。
但是,我不确定如何测试自定义错误消息。我看到了很多使用函数,但几乎没有用于类。
这是错误消息
Matcher error: received value must be a function
Received has type: string
Received has value: "1"
这是我的代码
unit_test.ts
describe("GET: search/api", () => {
class MyClass {
@IsDefined()
@Validate(DateConditionCheck, {
message: 'Please check your date input!'
})
dd: number;
};
const model: any = new MyClass ();
model.dd = 1;
it('should throw an error message when date input is incorrect', async () => {
return validate(model).then(errors => {
expect(errors.length).toBe(1);
expect(model.dd).toThrow('Date condition seems wrong!');
});
});
});
日期条件检查.ts
import {
IsDefined,
IsBoolean,
IsString,
IsEmail,
IsNumberString,
IsAlphanumeric,
IsNotEmpty,
MaxLength,
MinLength,
IsNumber,
IsEnum,
IsOptional,
Max,
Min,
Length,
Matches,
Validate,
ValidatorConstraint,
ValidatorConstraintInterface,
ValidationArguments,
registerDecorator,
ValidationOptions
} from 'class-validator'
import * as moment from 'moment'
/**
* Custom validator
*
*/
@ValidatorConstraint({ name: 'dateConditionCheck', async: false })
export class DateConditionCheck implements ValidatorConstraintInterface {
validate(text: any, args: ValidationArguments) {
const jsondata = JSON.parse(JSON.stringify(args.object))
if (args.property === 'dd') {
return moment(Number(jsondata.yyyy) + '-' + Number(jsondata.mm) + '-' + Number(jsondata.dd), 'YYYYMMDD').isValid()
}
if (args.property === 'dd2') {
return moment(
Number(jsondata.yyyy2) + '-' + Number(jsondata.mm2) + '-' + Number(jsondata.dd2),
'YYYYMMDD'
).isValid()
}
return true
}
defaultMessage(args: ValidationArguments) {
return 'Please check your date input!'
}
}
如果您需要任何额外信息,请告诉我。感谢您的所有帮助!