单元测试指令HostListener无法正常工作

时间:2018-01-24 16:04:18

标签: angular unit-testing typescript angular2-forms angular2-directives

我正在尝试对一些功能进行单元测试,这些功能在前端完美无缺,但单元测试似乎并没有成功。

以下是我当前的单元测试,它没有完全完成我只是想让裸骨测试工作,然后再进行更复杂的检查。

@Component({
  template : '<input appInputFilter filterType="alphanumericOnly" type="text" minlength="2">'
})
class TestComponent {

}

describe('InputFilterDirective', () => {

  let comp: TestComponent;
  let fixture: ComponentFixture<TestComponent>;
  let de: DebugElement;
 // const el: HTMLElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations : [InputFilterDirective, TestComponent]
    });

    fixture = TestBed.createComponent(TestComponent);

    comp = fixture.componentInstance;

    de = fixture.debugElement.query(By.directive(InputFilterDirective));
  });

  it('should create instance of inputFilter', () => {
    expect(comp).toBeTruthy();
    expect(de).toBeDefined();
  });

  it('should only allow onlyNumbers', async(() => {

    fixture.detectChanges();


    const keyEvent = new KeyboardEvent('keydown', {'code': 'KeyQ'});
    const input = de.nativeElement as HTMLInputElement;
    input.dispatchEvent(keyEvent);
    expect(input.value).toEqual('q');


    expect(true).toBeTruthy();
  }));
});

这是我的完整指示:

 import { Directive, ElementRef, HostListener, Input  } from '@angular/core';

@Directive({
  selector: '[appInputFilter]',

})
export class InputFilterDirective {

  private el : any;
  private specialKeys : Array<string> = ['Backspace', 'Tab', 'End', 'Home'];

  @Input() public filterType : any;

  constructor(el: ElementRef) {
    this.el = el;
   }

   @HostListener('keydown', ['$event'])
   onKeyDown(event: KeyboardEvent) {

    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }

    switch (this.filterType) {
      case 'onlyNumber':
        this.appFilter(event, new RegExp(/\D/g));
      break;
      case 'alphanumericOnly':
        this.appFilter(event, new RegExp(/\W/g));
      break;
      case 'alphabeticAndSpecial':
        this.appFilter(event, new RegExp(/[^a-zA-Z'-]/));
      break;
      case 'ipAddress':
        this.appFilter(event, new RegExp(/[^0-9.]/g));
      break;
    }
   };

  appFilter(event: KeyboardEvent, regex: RegExp) {
    const current: string = this.el.nativeElement.value;
    const next: string = current.concat(event.key);

    if (next && String(next).match(regex)) {
      event.preventDefault();
    }
  };
}

附加说明:

  • 我尝试了许多不同的KeyEvent,例如类型键:'1'等等。
  • 我已经将单元测试作为异步和非异步运行。
  • 关于其他人如何尝试对HostListeners进行单元测试,我遵循了许多不同的堆栈溢出指令,不幸的是,这根本不适合我,我不明白为什么。

非常感谢帮助,就像我说这是一个简单的骨骼测试,你会在测试组件中注意到我使用过滤器来过滤字母数字(你可以在指令代码中查看)

此外,我反对听“preventDefault”来证明这个测试,所以如果问题是我如何检测变化那么请告诉我,我不介意调整。

1 个答案:

答案 0 :(得分:0)

我很幸运在指令元素上使用triggerEventHandler。例如,

it('should add "c2d-dropzone-active" class to element when dragenter has occurred', async done => {
  fixture.detectChanges();
  const el: any = element.query(By.directive(C2dDropzoneDirective));
  expect(el.nativeElement.className).not.toContain('c2d-dropzone-active');
  el.triggerEventHandler('dragenter', mockEvent);
  fixture.detectChanges();
  await fixture.whenStable();
  expect(el.nativeElement.className).toContain('c2d-dropzone-active');
  done();
});