简体   繁体   English

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

[英]How do I trigger a keyboard event in an Angular 2+ unit test?

I have an Angular 4 component that listens for users pressing arrow keys. 我有一个Angular 4组件,可以监听用户按下箭头键的情况。 I have re-created it as a demo of a counter that you can increment or decrement using the up and down keys. 我已将其重新创建为计数器的演示,可以使用向上和向下键递增或递减。

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

}

I check this behaviour in a unit test: 我在单元测试中检查此行为:

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

This test fails. 该测试失败。 The counter is not incremented. 计数器不增加。 Why is that? 这是为什么?

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

尝试这个:

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

I have not yet found a way to do it through the debugElement, but I got it working using the window object: 我还没有找到一种通过debugElement做到这一点的方法,但是我使用window对象使其工作了:

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

consider, i have input field with class name '.search-input' then 考虑,我有类名为“ .search-input”的输入字段,然后

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

This is how i do it and it works for me. 这就是我的方法,对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM