Angular2如何对自定义验证器指令进行单元测试? [英] Angular2 how to unit test a custom validator directive?

查看:94
本文介绍了Angular2如何对自定义验证器指令进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wrote a very simple custom validor for an input field:

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上阅读了测试属性指令.页,但没有更改的CSS或html.如何对这个验证器进行单元测试?

I would like to unittest this validator. I read Test an attribute directive on the Angular2 page, but there is no css or html that changes. How can I unittest this validator?

推荐答案

如果您想以简单的方式进行操作(我会这样做,因为所有逻辑都在验证器函数中),仅用于测试验证器函数.只需将控件传递给它

If you want to do it the easy way (which I would do, since all the logic is in the validator function), is just to test the validator function. Just pass a control to it

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

如果您真的想在被使用"时对其进行测试,那么它会有些乏味.这些通常是我要采取的步骤

If you really want to test it when "being used", then it gets a little tedious. These are usually the steps I take

  1. 创建虚拟组件以使用指令
  2. 设置测试台配置
  3. 创建要测试的组件.
  4. 获取本机输入元素并为其分配无效的输入事件
  5. 获取装有NgForm
  6. 的进样器
  7. 检查表单是否失败
  8. 输入有效输入并检查其是否通过.
  1. Create dummy component to use the directive
  2. Set up the test bed configuration
  3. Create the component to test.
  4. Get the native input element and dispatch an invalid input event to it
  5. Get the injector that holds the NgForm
  6. Check the form for failure
  7. Put a valid input and check that it passes.

与仅测试验证器方法相比,有很多东西.但是无论如何,这还是;-)尽情享受吧!

It's a lot compared to just testing the validator method. But here it is anyway ;-) Enjoy!

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

这篇关于Angular2如何对自定义验证器指令进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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