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

问题描述 投票:0回答:1

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

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不是一个函数。

angular typescript unit-testing karma-jasmine angular-testing
1个回答
0
投票

您将需要将验证器应用于FormGroup,这将使您可以访问所需的FormControl。目前,您正在传递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 };
};
© www.soinside.com 2019 - 2024. All rights reserved.