MD10
MD10

Reputation: 1531

form control is always pending in async validator

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 

Upvotes: 0

Views: 1908

Answers (1)

uminder
uminder

Reputation: 26170

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

Upvotes: 2

Related Questions