我具有此功能,该功能检查password
和confirmPassword
字段的值是否相同。如果没有,则将该表单标记为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
! (见图)
我看到confirmPassword
字段没有被触摸。我在做什么错了?
答案 0 :(得分:0)
在设置其值之前,我不得不将该字段标记为脏
formControls['confirmPassword'].markAsTouched({onlySelf:true});
formControls['confirmPassword'].setValue("aA1!11112");
似乎setValue
正在运行表单验证,并且由于当时未将该字段标记为已触摸,因此confirmPasswordValidator
由Angular运行,并返回null
使该表单有效。调用markAsTouched
不会重新运行表单验证,然后addUser
会找到有效的表单。