Getting TypeError:control.get不是角度单元测试中的函数



我正在为密码编写角度单元测试用例,并确认密码验证。

validation.ts文件

export function matchPasswords(
passwordFieldName: string,
confirmPasswordFieldName: string
): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
const password = control.get(passwordFieldName).value;
const confirmPassword = control.get(confirmPasswordFieldName).value;
if (password !== confirmPassword) {
control
.get(confirmPasswordFieldName)
.setErrors({ passwordsDoNotMatch: true });
return { passwordsDoNotMatch: true };
} else {
return null;
}
};
}

validation.spec.ts代码

it('should match both password fields and return null if both matches', () => {
var passwordField1: string = "Admins@123";
var confirmPasswordField1: string = "Admins@123";
const validate = formValidators.matchPasswords(passwordField1, confirmPasswordField1);
const validate = formValidators.matchPasswords(passwordField1, confirmPasswordField1);
expect(
validate({value:{
'passwordFieldName':passwordField1,
'confirmPasswordFieldName':confirmPasswordField1}} as AbstractControl)
.toEqual(null));
});

在control.get(passwordFieldName(.value行,我得到了错误control.get不是一个函数。

您需要将验证器应用于FormGroup,这将使您能够访问所需的FormControls。目前,您正在传递AbstractControl/FormControl,它本质上是一个单一的表单字段。

函数可能看起来有点像这样。

export function matchPasswords: ValidatorFn = (fg: FormGroup) => {
const password = fg.get('passwordFieldName').value;
const confirmPassword = fg.get('confirmPasswordFieldName').value;
return password === confirmPassword
? null
: { passwordsDoNotMatch: true };
};

最新更新