unit-testing - Angular2 如何对自定义验证器指令进行单元测试?

标签 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 {}

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

最佳答案

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

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

如果你真的想在“被使用”时测试它,那就有点乏味了。这些通常是我采取的步骤

  1. 创建虚拟组件以使用指令
  2. 设置测试台配置
  3. 创建要测试的组件。
  4. 获取 native 输入元素并向其分派(dispatch)无效输入事件
  5. 获取包含 NgForm 的注入(inject)器
  6. 检查表单是否失败
  7. 输入一个有效的输入并检查它是否通过。

与仅测试验证器方法相比,这已经很多了。但无论如何它就在这里 ;-) 尽情享受吧!

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

关于unit-testing - Angular2 如何对自定义验证器指令进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39957799/

相关文章:

python - 如何从打印消息并关闭程序的函数创建单元测试?

javascript - 如何在带有 Electron 和 NodeJs 8 的 Angular 7 中通过 Jest 迁移或使用现有的 karma Jasmine

angularjs - 如何使用 Jasmine 的 debounce 功能测试 AngularJS watch

javascript - 开 Jest : return a value from a test

iOS UITests - XCUIElements 标识符的用途

html - Angular 中的 float 面板

angular - 构建错误 - JSON 中位置 0 处出现意外 token

angular - Angular 未检测到从 Ngxs 状态发出的 Http 请求(与区域相关的问题)

angular - karma : How to handle multiple calls to a spy that have different responses?

unit-testing - 我如何对相对性能进行单元测试?