表单控件始终在异步验证器中挂起

form control is always pending in async validator

我有一个表单控件如下: ....

direction: new Form("", [Validators.pattern("^[0-9]*$")],[requiredAsyncValidator])

并且所需的 AsyncValidator 是

export const requiredAsyncValidator = (control:FormControl):Promise<any> | Observable<any> => {
   return new Promise<any>((resolve,reject) => {
     setTimeout(() => {
        if(control.value == '' && control.touched) {
           resolve({required:true})
        }
        else{
          resolve(null)
        },100)
})
}

在我的 html 中,我已将 (blur)="direction.updateValueAndValidity()" 附加到控件 然而,当我想在我的规范文件中测试它时,我在该控件上获得了 PENDING 状态,因此我的表单无效 这是我的测试:

component.direction.setValue(12)
component.direction.updateValueAndValidity()
fixture.detectChanges()
expect(component.form.valid).toBeTruthy() // false because direction field is PENDING 

将您的测试函数包装到 fakeAsync 中,使其在 fakeAsync 区域中执行。然后使用 flushfakeAsync 区域中的计时器模拟时间的异步流逝。

import { fakeAsync, flush } from '@angular/core/testing';
...

it('...', fakeAsync(() => {
    component.direction.setValue(12);
    component.direction.updateValueAndValidity();
    flush(); 
    fixture.detectChanges();
    expect(component.form.valid).toBeTruthy();   
}));

作为替代方案,您可以使用一种 Jasmine 特定方法来测试异步代码(请参阅 https://jasmine.github.io/tutorials/async)。