3

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...

1
  • 1
    Make the test async. Commented Jul 17, 2017 at 6:30

1 Answer 1

4

I had to change it to an Async test. Thanks to @peeskillet ! Also I had to change "key": "escape" to "code": "ESCAPE"

it('should trigger escape event', async(() => {
        component.formProps.ausgeklappt = true;
        fixture.detectChanges();
        let spy = spyOn(component, "closeForm");
        const event = new KeyboardEvent("keypress",{
          "code": "ESCAPE",
        });
        fixture.nativeElement.dispatchEvent(event);

        component.keyboardInput(event);
        expect(spy).toHaveBeenCalled();
      }));
Sign up to request clarification or add additional context in comments.

2 Comments

Important part: You have to call the handler itself as well component.keyboardInput(event), just dispatching the event is not enough.
for that very reason am doubtful about this solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.