Angular2如何单元测试自定义验证器指令?

时间:2016-10-10 11:59:52

标签: unit-testing angular karma-jasmine angular2-forms angular2-testing

我为输入字段编写了一个非常简单的自定义验证器:

import { Directive } from '@angular/core';
import { AbstractControl, NG_VALIDATORS } from '@angular/forms';

function numberValidator(c: AbstractControl) {
    if (!c.value) return null;
    return new RegExp('^[1-9][0-9]{6,9}$').test(c.value) ? null : {
        validateNumber: {
            valid: false
        }
    }
}

@Directive({
    selector: '[number-validator]',
    providers: [
        { provide: NG_VALIDATORS, multi: true, useValue: numberValidator }
    ]
})
export class NumberValidator {

}

我想对这个验证器进行单元测试。我在Angular2页面上阅读Test an attribute directive,但没有更改的css或html。我该如何对这个验证器进行单元测试?

1 个答案:

答案 0 :(得分:16)

如果你想以简单的方式(我会这样做,因为所有逻辑都在验证器函数中),只是为了测试验证器函数。只需将控件传递给它

expect(numberValidator(new FormControl('123456'))).toEqual({
  'validateNumber': { 'valid': false }
});
expect(numberValidator(new FormControl('123456789'))).toEqual(null);

如果您真的想在"正在使用"时进行测试,那么它会变得有点单调乏味。这些通常是我采取的步骤

  1. 创建虚拟组件以使用指令
  2. 设置测试台配置
  3. 创建要测试的组件。
  4. 获取原生输入元素并向其发送无效的输入事件
  5. 获取包含NgForm
  6. 的注射器
  7. 检查表单是否失败
  8. 输入有效的输入并检查它是否通过。
  9. 与仅测试验证器方法相比,它有很多。但无论如何它在这里;-)享受!

    import { Component, Directive } from '@angular/core';
    import { TestBed, async } from '@angular/core/testing';
    import { dispatchEvent } from '@angular/platform-browser/testing/browser_util';
    import { By } from '@angular/platform-browser';
    import { FormsModule, NG_VALIDATORS, AbstractControl,
             NgForm, FormControl } from '@angular/forms';
    
    function numberValidator(c: AbstractControl) {
      if (!c.value) return null;
      return new RegExp('^[1-9][0-9]{6,9}$').test(c.value) ? null : {
        validateNumber: {
          valid: false
        }
      };
    }
    
    @Directive({
      selector: '[number-validator]',
      providers: [
        { provide: NG_VALIDATORS, multi: true, useValue: numberValidator }
      ]
    })
    export class NumberValidator {
    }
    
    @Component({
      template: `
        <form>
          <input name="number" type="text" ngModel number-validator />
        </form>
      `
    })
    class TestComponent {
    }
    
    describe('component: TestComponent', () => {
      beforeEach(() => {
        TestBed.configureTestingModule({
          imports: [ FormsModule ],
          declarations: [TestComponent, NumberValidator]
        });
      });
    
      it('should validate (easy)', () => {
        expect(numberValidator(new FormControl('123'))).toEqual({
          'validateNumber': { 'valid': false }
        });
        expect(numberValidator(new FormControl('123456789'))).toEqual(null);
      });
    
      it('should validate (tedious)', async(() => {
        let fixture = TestBed.createComponent(TestComponent);
        let comp = fixture.componentInstance;
        let debug = fixture.debugElement;
        let input = debug.query(By.css('[name=number]'));
    
        fixture.detectChanges();
        fixture.whenStable().then(() => {
          input.nativeElement.value = '123';
          dispatchEvent(input.nativeElement, 'input');
          fixture.detectChanges();
    
          let form: NgForm = debug.children[0].injector.get(NgForm);
          let control = form.control.get('number');
    
          // just to show a few different ways we can check validity
          expect(control.hasError('validateNumber')).toBe(true);
          expect(control.valid).toBe(false);
          expect(form.control.valid).toEqual(false);
          expect(form.control.hasError('validateNumber', ['number'])).toEqual(true);
    
          input.nativeElement.value = '123456789';
          dispatchEvent(input.nativeElement, 'input');
          fixture.detectChanges();
    
          expect(form.control.valid).toEqual(true);
        });
      }));
    });