我有一个表单控件,如下所示: ....
direction: new Form("", [Validators.pattern("^[0-9]*$")],[requiredAsyncValidator])
并且所需的异步验证器是
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
区域中执行。然后使用flush
模拟fakeAsync
区域中计时器的异步时间流逝。
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(。