首页 > 解决方案 > 用于上下箭头键盘事件的 Jasmine 测试用例

问题描述

我正在尝试为自动完成组件的键盘事件编写单元测试用例。当用户按下 keyup 和 keydown 从下拉列表中选择值时,将调用以下函数:

onKeyDown(event:KeyboardEvent){
    if(event.which !== 40 && event.which !== 38){
        return;
    }

    event.stopPropagation();
    if (event.which === 40 && this.arrowkeylocation < this.suggestionArray.length - 1) {
        // Arrow Down
        this.arrowkeylocation++;
        this.textSearch = this.suggestionArray[this.arrowkeylocation].title;
    } else if (event.which === 38 && this.arrowkeylocation > 0) {
        // Arrow Up
        this.arrowkeylocation--;
        this.textSearch = this.suggestionArray[this.arrowkeylocation].title;
    }      
}

以下是不起作用的测试用例:

it('should call onKeyDown 40 event', () => {
    const keyevent = {keyCode: 40};
    component.suggestionArray = [suggest,suggest];
    inputEl.triggerEventHandler('keydown',keyevent);
    expect(component.onKeyDown).toBeTruthy();
    expect(component.arrowkeylocation).toEqual(0);  
expect(component.textSearch).toEqual(component.suggestionArray[0].title);        
});

当用户按下 keyup 或 keydown 时,arrowkeylocation 计数器初始化为 -1 以自动完成文本框值。建议数组是自动完成下拉值。

标签: angularjasminekarma-jasmine

解决方案


推荐阅读