我有一个函数,它检测按键,并且如果按下的键等于 escape,则会触发一个函数。
我遇到了模拟传递按键事件的问题。
我看到了这个帖子:(链接) ,但是实现此解决方法会输出以下内容(我在控制台记录了事件本身):
LOG: KeyboardEvent{isTrusted: false} Chrome 68.0.3440 (Mac OS X 10.13.6) ConfirmationComponent should call onDeny when ESCAPE button pressed FAILED Expected spy onDeny to have been called.
component.ts
@HostListener('window:keyup', ['$event'])
keyEvent(event: KeyboardEvent) {
console.log(event);
// Press escape - close dialog with simulated 'cancel' click
if (event.code === 'Escape') {
this.onDeny();
}
}
onDeny() {
// something is done here
}
test.ts
it('should autofocus on cancel button on init', () => {
spyOn(component, 'onDeny');
component.keyEvent(ESCAPE);
expect(component.onDeny).toHaveBeenCalled();
});
keycode
而不是code
。但是,是的,按照你的建议,将其更加通用化会更好。 - physicsboyKeyboardEvent
转换为ngKeyEvent
,您尝试模拟键盘事件,它永远不会起作用。这就是为什么单元测试测试单个单元并模拟依赖项:它们必须抽象化它们的行为! - user4676340const evt = new KeybaordEvent('keydown', {code: 'Escape'})
抽象为const evt = ngEvent.keyboard.create('Escape')
。由于您实际上不知道它的作用,最好的方法是测试您所控制的内容,也就是您自己的代码。 - user4676340