我有一个指令,它侦听按键事件以便在按下Enter键时采取措施,还有一个使用它的组件:
onEnter指令
@Directive({
selector: '[appOnEnter]'
})
export class OnEnterDirective {
@Output() enterPressed = new EventEmitter();
@HostListener('document:keydown', ['$event'])
onKeyPress(event: KeyboardEvent) {
if ((event.which === 13)) {
this.enterPressed.emit();
}
}
}
component.html
<div appOnEnter (enterPressed)=do()></div>
component.ts
export class Component {
next = new EventEmitter<null>();
do() {
this.next.emit();
}
}
我正在尝试用茉莉花对此进行测试,但似乎未触发该事件。
component.spec.ts
it('if enter is pressed action should be taken', () => {
spyOn(component.next, 'emit');
const event = new KeyboardEvent('keypress', {
key: 'Enter'
});
fixture.detectChanges();
expect(component.next.emit).toHaveBeenCalled();
});
组件和指令工作正常,唯一的问题是模拟enter键。