form control is always pending in async validator

一曲冷凌霜 提交于 2020-01-16 19:37:14

问题


I have a form control that is as following: ....

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

and the requiredAsyncValidator is

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)
})
}

in my html I have attached (blur)="direction.updateValueAndValidity()" to the control however when I want to test it in my spec file I am getting PENDING state on that control and thus my form is not valid this is my test:

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

回答1:


Wrap your test function into fakeAsync to have it executed in the fakeAsync zone. Then use flush to simulates the asynchronous passage of time for the timers in the fakeAsync zone.

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

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

As an alternative you may use one of the Jasmine specific ways of testing asynchronous code (see https://jasmine.github.io/tutorials/async).



来源:https://stackoverflow.com/questions/59542020/form-control-is-always-pending-in-async-validator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!