Angular的FormControl方法markAsTouched在测试用例中不起作用

时间:2019-08-17 20:18:46

标签: angular6 angular-testing

我具有此功能,该功能检查passwordconfirmPassword字段的值是否相同。如果没有,则将该表单标记为invalid

confirmPasswordValidator(passwordGroupForm: AbstractControl){

    let password = passwordGroupForm.get('password');
    let confirmPassword = passwordGroupForm.get('confirmPassword');
    console.log("password is "+password +"and confirmPassword is "+confirmPassword);


    console.log("confirm password touched",confirmPassword.touched );
    if(!confirmPassword.touched) return null ;//don't mark form invalid if the user hasn't interacted with confirmPassword field
    else {
      return (password.value === confirmPassword.value) ? null : {
          confirmPasswordValidator: {
            valid: false,
            message: 'Password and Verify Password fields do not match'
          }
        }
      }
    }

我编写了以下测试用例,以检查该功能是否正常工作。

it('should not submit form if password and confirm password are not the same',()=>{
    let formControls = component.signupForm.controls;
    let userService = TestBed.get(UserManagementService);
    spyOn(userService,'addUser');
    formControls['firstName'].setValue("first");
    formControls['lastName'].setValue("last");
    formControls['email'].setValue("e@e.com");
    formControls['password'].setValue("aA1!1111");
    formControls['confirmPassword'].setValue("aA1!11112");

    fixture.detectChanges();
    formControls['confirmPassword'].markAsTouched();
console.log("after control touched, touch value is",formControls['confirmPassword'].markAsTouched());
    component.addUser();
    expect(component.signupForm.valid).toBeFalsy();
    expect(userService.addUser).not.toHaveBeenCalled();
  });

但是测试用例失败,错误为Expected true to be falsy.在浏览器窗口中,我看到它显示touched属性为true以及false! (见图)

enter image description here

我看到confirmPassword字段没有被触摸。我在做什么错了?

1 个答案:

答案 0 :(得分:0)

在设置其值之前,我不得不将该字段标记为脏

formControls['confirmPassword'].markAsTouched({onlySelf:true});
    formControls['confirmPassword'].setValue("aA1!11112");

似乎setValue正在运行表单验证,并且由于当时未将该字段标记为已触摸,因此confirmPasswordValidator由Angular运行,并返回null使该表单有效。调用markAsTouched不会重新运行表单验证,然后addUser会找到有效的表单。