问题描述
我的组件中有以下代码
@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();
});