【问题标题】:Getting TypeError: control.get is not a function in Angular Unit Testing获取 TypeError:control.get 不是 Angular 单元测试中的函数
【发布时间】:2020-03-18 14:21:41
【问题描述】:

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

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 is not a function。

【问题讨论】:

    标签: angular typescript unit-testing karma-jasmine angular-test


    【解决方案1】:

    您需要将验证器应用到 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 };
    };
    

    【讨论】:

    • 我必须编写单元测试用例。我无法修改现有的 TS 文件代码。我只需要更改 spec.ts 文件
    猜你喜欢
    • 1970-01-01
    • 2018-11-29
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    相关资源
    最近更新 更多