Man*_*dha 4 angular-test angular6
我有这个函数来检查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'
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我编写了以下测试用例来检查该功能是否有效。
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();
});
Run Code Online (Sandbox Code Playgroud)
但测试用例失败并出现错误Expected true to be falsy.在浏览器窗口中我可以看到它正在显示touched属性true以及false!!(见图)
我可以看到该confirmPassword字段没有被触及。我究竟做错了什么?
在设置其值之前我必须将该字段标记为脏
formControls['confirmPassword'].markAsTouched({onlySelf:true});
formControls['confirmPassword'].setValue("aA1!11112");
Run Code Online (Sandbox Code Playgroud)
它似乎setValue运行了表单验证,并且由于当时该字段未标记为触摸,因此confirmPasswordValidator由 Angular 运行并返回,null使表单有效。调用markAsTouched不会重新运行表单验证,addUser然后发现表单有效。
| 归档时间: |
|
| 查看次数: |
11647 次 |
| 最近记录: |