如何为角度输入元素的Hostlistener指令创建单元测试?

时间:2018-11-28 11:52:55

标签: jasmine angular6 directive angular-directive

我需要为下面的指令创建单元测试,该指令是在angular 6中发生hostlistener事件。

在这里,我们需要检查输入并提供电话号码屏蔽,并且我需要在茉莉花中创建测试用例以检查其覆盖范围。

我正在尝试通过测试用例来验证逻辑,但通过onModelChange指令方法上的调度事件无法调用,并且无法从指令中获取更新的掩码值。

//Below is my directive:

import { Directive, HostListener, forwardRef, ElementRef } from '@angular/core';
import { Validator, FormControl, NG_VALIDATORS } from '@angular/forms';

@Directive({
  selector: '[appTelephoneFormat]',
  providers: [
    { provide: NG_VALIDATORS, useExisting: forwardRef(() => TelephoneFormatDirective), multi: true }
]
})
export class TelephoneFormatDirective implements Validator {

  constructor(private elem: ElementRef) {
  }

  @HostListener('ngModelChange', ['$event'])
  public onModelChange(event: Event) {
    console.log('Function Called');
    this.onInputChange(event, false);
  }

  @HostListener('keydown.backspace', ['$event'])
  public keydownBackspace(event) {
    this.onInputChange(event.target.value, true);
  }

  public onInputChange(event, backspace) {
    let newVal = event.replace(/\D/g, '');
    if (backspace && newVal.length <= 6) {
      newVal = newVal.substring(0, newVal.length - 1);
    }
    if (newVal.length === 0) {
      newVal = '';
    } else if (newVal.length <= 3) {
      newVal = newVal.replace(/^(\d{0,3})/, '($1)');
    } else if (newVal.length <= 6) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '($1) ($2)');
    } else if (newVal.length <= 10) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '($1) ($2)-$3');
    } else {
      newVal = newVal.substring(0, 10);
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '($1) ($2)-$3');
    }
    this.elem.nativeElement.value = newVal;
  }

  public validate(input: FormControl): { [key: string]: boolean } {

    const numberEntered: string = input.value.replace(/[^0-9]/g, '');
    let validity: { [key: string]: boolean } = null;

    if (numberEntered.length < 10) {
      validity = { telephoneFormatError: true };
    }

    return validity;
  }

}

我正在尝试使用此规范,但它并未调用我的指令方法:

import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { Component, DebugElement } from '@angular/core';
import { TelephoneFormatDirective } from './telephone-format.directive';
import { By } from '@angular/platform-browser';


@Component({
  template: '<input type="text appTelephoneFormat">'
})

export class TestTelephoneFormatComponent {
}

describe('Directive: Telehpone Number', () => {

  let component: TestTelephoneFormatComponent;
  let fixture: ComponentFixture<TestTelephoneFormatComponent>;
  let inputEl: DebugElement;
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [TestTelephoneFormatComponent, TelephoneFormatDirective]
    });
    fixture = TestBed.createComponent(TestTelephoneFormatComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    inputEl = fixture.debugElement.query(By.css('input'));
  });

  it('test input with equal or less than 6 characters', async(() => {
    inputEl.nativeElement.value = '123456';
    fixture.detectChanges();
    inputEl.nativeElement.dispatchEvent(new Event('ngModelChange'));
    fixture.detectChanges();
    expect(inputEl.nativeElement.value).toBe('(123)(456)');
}));

});

0 个答案:

没有答案