简体   繁体   中英

Angular unit test case for @HostListener escape key event

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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