Angular @HostListener 转义键事件的单元测试用例

Angular unit test case for @HostListener escape key event

我的组件中有以下代码

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

我使用ngneat spectator作为我的单元测试框架,下面是我的测试用例需要更正

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

这里我无法理解如何模拟转义键事件。任何帮助,将不胜感激。谢谢

您快完成了,只差最后一步。你需要用新创建的键盘事件调用onKeydownHandler方法:

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