根据我的理解,我认为装饰器应该进行e2e测试,而不是单元测试。但是我创建了一个自定义的装饰器。该方案与电话号码有关。根据加载的环境,仅基于有限数量的电话号码的提供者可以接受。我结束了以下内容:
import { registerDecorator, ValidationOptions, ValidationArguments } from 'class-validator';
import { settings } from "../config/settings";
export function IsValidPhoneNumber(property: string, validationOptions?: ValidationOptions) {
return function (object: Object, propertyName: string) {
registerDecorator({
name: 'isValidPhoneNumber',
target: object.constructor,
propertyName: propertyName,
constraints: [property],
options: validationOptions ? validationOptions : { message : "invalidPhoneNumber"} ,
validator: {
validate(value: any, args: ValidationArguments) {
let allowedPhoneProvider = false;
if (phoneIsValidBasedOnEnv){
allowedPhoneProvider = true
}
return typeof value === 'string' && allowedPhoneProvider;
},
},
});
};
}
现在进入我的dto:
import { IsValidPhoneNumber } from "./phone-validator";
export class BookDto {
@IsNotEmpty()
@IsValidPhoneNumber('phone')
phone : string;
}
现在我在为IsValidPhoneNumber()编写测试中迷路了。我有以下内容:
import { IsValidPhoneNumber } from './phone-validator';
describe("Validators", () =>{
it("should return true for valid numbers", () =>{
const b = IsValidPhoneNumber("phone");
console.log(b({"phoone":"098548000","phone"});
})
})
我阅读了以下有关使用工厂测试装饰器的信息,但args始终未定义。
import { ROUTE_ARGS_METADATA } from '@nestjs/common/constants';
function getParamDecoratorFactory(decorator: Function) {
class Test {
public test(@decorator() value) { }
}
const args = Reflect.getMetadata(ROUTE_ARGS_METADATA, Test, 'test');
// args is undefined
return args[Object.keys(args)[0]].factory;
}