Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 unit test: How to test keyboard input

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

like image 263
BearBytes Avatar asked May 12 '26 13:05

BearBytes


1 Answers

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();
      }));
like image 141
BearBytes Avatar answered May 15 '26 05:05

BearBytes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!