角度2单元测试:如何测试键盘输入

时间:2017-07-13 12:37:48

标签: angular unit-testing

我正在尝试为键盘输入编写单元测试。在我的组件中,我有这个函数来捕获我的键盘事件:

@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();
    }
  }

我试图模拟'逃脱'事件,但失败了。 我的component.spec.ts看起来像这样:

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();
  });

我不知道如何解决这个问题,我很感谢每一个帮助...

1 个答案:

答案 0 :(得分:4)

我不得不将其更改为异步测试。感谢@peeskillet! 另外,我必须将import QtQuick 2.9 import QtQuick.Controls 2.2 ApplicationWindow { id: mainWindow visible: true width: 400 height: 400 Path { id: myPath startX: 0; startY: 20 PathCurve { x: 100; y: 40 } PathCurve { x: 200; y: 10 } PathCurve { x: 300; y: 40 } } Slider { id: control width: 300 height: 50 anchors.centerIn: parent background: Rectangle { anchors.fill: parent color: "orange" Canvas { anchors.fill: parent contextType: "2d" onPaint: { context.strokeStyle = "MediumPurple"; context.path = myPath; context.stroke(); } } PathInterpolator { id: motionPath path: myPath progress: control.visualPosition } } handle: Rectangle { width: 30 height: 30 radius: 15 color: "DodgerBlue" x: motionPath.x - 15 y: motionPath.y - 15 } } } 更改为"key": "escape"

"code": "ESCAPE"