如何在Angular 2+单元测试中触发键盘事件?

时间:2018-01-24 13:36:59

标签: angular unit-testing

我有一个Angular 4组件,用于按下箭头键来监听用户。我重新创建了它作为计数器的演示,你可以使用向上和向下键增加或减少。

export enum KEY_CODE {
  RIGHT_ARROW = 39,
  LEFT_ARROW = 37
};

export class AppComponent {    
  counter = 0;

 @HostListener('window:keyup', ['$event'])
  handleKeypress(event: KeyboardEvent) {
    if (event.keyCode === KEY_CODE.UP_ARROW) {
      this.counter++;
    } else if (event.keyCode === KEY_CODE.DOWN_ARROW) {
      this.counter--;
    }
  }

}

我在单元测试中检查这种行为:

  it('should increment when you push the "up" key', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;

    expect(app.counter).toBe(0);
    let upKeyPress = {keyCode: KEY_CODE.UP_ARROW};
    fixture.debugElement.triggerEventHandler('keyup', upKeyPress);
    expect(app.counter).toBe(1);
  });

此测试失败。计数器不会递增。那是为什么?

Plunker: https://plnkr.co/edit/sNtQMH82Tk2siKueBDT5?p=preview

3 个答案:

答案 0 :(得分:0)

试试这个:

fixture.debugElement.triggerEventHandler('keyup.uparrow', {}});

答案 1 :(得分:0)

我还没有通过debugElement找到一种方法,但是我使用window对象来实现它:

let upPress = new KeyboardEvent('keyup', {code: 'ArrowUp'});
window.dispatchEvent(upPress);

答案 2 :(得分:0)

考虑,我有一个类名为“ .search-input”的输入字段 然后

const element = fixture.debugElement.query(By.css('.search-input'));
element.nativeElement.dispatchEvent(new KeyboardEvent('keyup', {code: 'ArrowUp'}));
fixture.detectChanges();

这就是我的方法,对我有用。