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

angular 6 keypress event
keyup.enter not working angular 6
mobile keyboard events
angular 2 test key press
keyboard events in javascript with example
angular unit test mock keyboard event
trigger keyboard event javascript
javascript dispatch enter key event

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


Try this:

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

Angular Quick Tip: Binding Specific Keys to the Keyup and Keydown , 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:  When binding to either the keyup or keydown events in your Angular 2+ templates, you can specify key names. This makes it very easy to trigger the event only when specific keys are pressed. This makes it very easy to trigger the event only when specific keys are pressed.


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

How do I trigger a keyboard event in an Angular 2+ unit test?, Learn how to listen to keyboard events with Angular and the Host Listener API. The content is likely be applicable for older Angular 2 or other triggers the event, Angular will call our keyEvent() method passing in the event. There are two ways to trigger events in unit tests. Let’s examine both of them. 1️⃣ Angular’s triggerEventHandler() Method. The Angular DebugElement instance provides a handy method for triggering events — triggerEventHandler(). Let’s see how we can use it.


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.

Listening to Angular Key Events with Host Listeners, A keyboard event is essentially a trigger than executes a bit of JavaScript code when a user presses a keyboard key. For example, you might  I am going to share with you a useful list of Angular 10/9/8 Event Types for Event Binding. Angular offers plenty of event types to communicate with your app. Events in Angular 7 helps you to trigger an action on specific condition like click, scroll, hover, focus, submit etc.


Angular 2 Keyboard Events 10+ Examples, Angular 2 - Key Event Filtering - The user can display the data of input box by pressing 'Enter' key on the keyboard. Angular 5 and higher version already has some event bindings to respond to any type of DOM event. Here we have to bind the click event to detect the click from the user. To bind the click event to the DOM, we have to surround the click event name in parentheses and pass a method name inside quotes after the equal sign after event name.


Angular 2 - Key Event Filtering, Many DOM events are triggered by user input. When a user presses and releases a key, the keyup event occurs, and Angular provides a corresponding DOM  Angular Quick Tip: Binding Specific Keys to the Keyup and Keydown Events When binding to either the keyup or keydown events in your Angular 2+ templates, you can specify key names. This makes it very easy to trigger the event only when specific keys are pressed. First, let’s see an example without using a key name.


User input, The following example registers another DOM event handler that listens for key-​press events. The method onFileChange ($event) displays the file name of the file being uploaded by assigning it on the variable tenantIDFileName. The method openFileBrowser ($event) triggers the click event on the file browser. Walkthrough of the Process When browse is clicked, openFileBrowser ($event) is called with $event as the argument.