Angular unit test case for @HostListener escape key event

2.1k views Asked by At

I have below code in my component

@HostListener('document:keydown', ['$event']) onKeydownHandler(event: KeyboardEvent) {
if (event.key === 'Escape') {
  this.showDialogPopup = false;
  this.showPortfolioDialogPopup = false;
}
}

And I am using ngneat spectator as my unit testing framework, below is my test case which needs to be corrected

it('Close popups on Escape key press', () => {
const keyboardEvent = createKeyboardEvent('keydown', 'Escape');
const spy = spyOn(keyboardEvent, 'preventDefault'); 
spectator.component.showPopup(false);  
spectator.component.showPortfolioPopup(false);
expect(spectator.component.showPortfolioDialogPopup).toBeFalsy();
expect(spectator.component.showDialogPopup).toBeFalsy();
});

Here I am not able to understand how to mock the escape key event. Any help would be appreciated. Thanks.

1

There are 1 answers

0
JSON Derulo On BEST ANSWER

You were almost there, just the last step missing. You need to call the onKeydownHandler method with the newly created keyboard event:

it('Close popups on Escape key press', () => {
  const keyboardEvent = createKeyboardEvent('keydown', 'Escape');
  spectator.component.onKeydownHandler(keyboardEvent);
  expect(spectator.component.showPortfolioDialogPopup).toBeFalsy();
  expect(spectator.component.showDialogPopup).toBeFalsy();
});