Angular6 角度';s FormControl方法MarkaTouched在测试用例中不起作用

Angular6 角度';s FormControl方法MarkaTouched在测试用例中不起作用,angular6,angular-test,Angular6,Angular Test,我有一个函数,它检查密码和确认密码字段是否具有相同的值。如果不是,则表单标记为无效 confirmPasswordValidator(passwordGroupForm: AbstractControl){ let password = passwordGroupForm.get('password'); let confirmPassword = passwordGroupForm.get('confirmPassword'); console.log("passwo

我有一个函数,它检查
密码
确认密码
字段是否具有相同的值。如果不是,则表单标记为
无效

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();
  });
但是测试用例失败了,错误
预期为true为false。
在浏览器窗口中,我可以看到它将
属性显示为
true
以及
false
!!(见图)


我可以看到,
confirmPassword
字段没有被触动。我做错了什么?

在设置字段值之前,我必须将其标记为脏字段

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

似乎
setValue
运行表单验证,由于当时字段未被标记为触动,因此
confirmPasswordValidator
按Angular运行,并返回
null
使表单有效。调用
markAsTouched
不会重新运行表单验证,并且
addUser
会发现表单有效。

有时需要调用setValue,有时不需要。。。