I'm trying to write a unit test for an keyboard input. Within my component I have this function to capture my keyboard events:
@HostListener('window:keydown', ['$event'])
keyboardInput(event: any){
if(event.code.toLowerCase()==="escape" && this.formProps.ausgeklappt){
this.closeForm();
} else if(event.code.toLowerCase()==="enter" && this.dayData.isSelected && !this.formProps.ausgeklappt) {
console.log("enter wurde gedrückt " + this.dayData.day);
this.handleHeaderClick();
}
}
I tried to simulate the 'escape' event, but failed miserably. My component.spec.ts looks like this:
it('should trigger escape event', () => {
component.formProps.ausgeklappt = true;
fixture.detectChanges();
let spy = spyOn(component, "closeForm");
const event = new KeyboardEvent("keypress",{
"key": "escape"
});
fixture.nativeElement.dispatchEvent(event)
component.keyboardInput(event);
expect(spy).toHaveBeenCalled();
});
I don't know how to solve this problem and I'm thankful for every help...