0

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.

vamsi
  • 1,488
  • 3
  • 28
  • 66

1 Answers1

0

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();
});
JSON Derulo
  • 9,780
  • 7
  • 39
  • 56