【问题标题】:How to write unit test case for a custom validator for angular reactive forms如何为角度反应形式的自定义验证器编写单元测试用例
【发布时间】:2021-12-22 22:12:15
【问题描述】:

如何为以下方法编写测试用例:

export class CustomErrorStateMatcher implements ErrorStatematcher {
isErrorState(control: FormControl,form:NgForm | FormGroupDirective | null){
return control && control.invalid && control.touched
}}

【问题讨论】:

    标签: angular typescript unit-testing jasmine karma-runner


    【解决方案1】:

    您可以创建控件的实例并在那里传递您的自定义验证器。然后给它赋值并测试预期的输出。

    这是一个例子:

    let control: FormControl;
    
    describe('Phone validator: ', () => {
      beforeAll(() => {
        control = new FormControl('', [phoneValidator]);
      });
    
      it('should validate phone', () => {
        control.setValue('not a phone number');
        expect(control.valid).toBe(false); // invalid phone number
    
        control.setValue('+49123456789');
        expect(control.valid).toBe(true); // valid phone number
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2018-04-28
      • 2017-10-06
      • 1970-01-01
      • 2020-05-02
      • 2018-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多