簡體   English   中英

Angular的FormControl方法markAsTouched在測試用例中不起作用

[英]Angular's FormControl method markAsTouched not working in a test case

我有此功能,用於檢查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屬性為truefalse (見圖)

在此處輸入圖片說明

我可以看到confirmPassword字段未被觸摸。 我究竟做錯了什么?

在設置其值之前,我不得不將該字段標記為臟

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

setValue似乎正在運行表單驗證,並且由於當時未將該字段標記為已觸摸,因此confirmPasswordValidator由Angular運行,並且它返回null使表單有效。 調用markAsTouched不會重新運行表單驗證,然后addUser會找到有效的表單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM