Stewart
Stewart

Reputation: 1899

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. 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

Upvotes: 1

Views: 7655

Answers (3)

Mayur Nandane
Mayur Nandane

Reputation: 317

consider, i have input field with class name '.search-input' then

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.

Upvotes: 2

Stewart
Stewart

Reputation: 1899

I have not yet found a way to do it through the debugElement, but I got it working using the window object:

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

Upvotes: 0

David Anthony Acosta
David Anthony Acosta

Reputation: 4908

Try this:

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

Upvotes: 1

Related Questions