表单控件始终在异步验证器中挂起 [英] form control is always pending in async validator

查看:70
本文介绍了表单控件始终在异步验证器中挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

在我的HTML中,我已将(blur)="direction.updateValueAndValidity()"附加到控件 但是,当我想在我的规格文件中对其进行测试时,该控件的状态为PENDING,因此我的表格无效 这是我的测试:

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 

推荐答案

将测试函数包装到fakeAsync中,以使其在

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

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

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

这篇关于表单控件始终在异步验证器中挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆