在angular2组件中对用户交互进行单元测试

时间:2017-02-17 17:34:49

标签: unit-testing angular jasmine

我最近开始学习angular2,我想我会尝试编写类似于select2的组合框组件。这是该组件的简化版本:

@Component({
    selector: 'combobox',
    template: `
        <div class="combobox-wrapper">
            <input type="text"></input>
            <button class="toggle-button"></button>
        </div>
        <div *ngIf="isDropdownOpen" class="dropdown">
            <div *ngFor="let option of options; let index = index;"
                class="option"
                [class.focused]="focusedIndex==index">
                {{option.label}}
            </div>
        </div>
    `
})
export class ComboboxComponent {
    @Input() options: any[] = [];
    isDropdownOpen: boolean = false;
    focusedIndex: number = 0;
}

在撰写涉及用户互动的单元测试时,我很挣扎。例如,我希望用户能够使用键盘上的向上和向下键导航选项列表。我看到它的方式,我有两个选择。

选项1:

describe('when the dropdown is open and the user presses the "UP" key', () => {
    it('should focus the first available preceeding option', () => {
        const button = fixture.debugElement.query(By.css('.toggle-button'));
        const input = fixture.debugElement.query(By.css('input'));

        button.triggerEventHandler('mousedown', {});
        input.triggerEventHandler('keydown', { key: 'ArrowDown' });
        input.triggerEventHandler('keydown', { key: 'ArrowDown' });
        input.triggerEventHandler('keydown', { key: 'ArrowUp' });
        fixture.detectChanges();

        const options = fixture.debugElement.queryAll(By.css('.option'));
        expect(options[1].nativeElement.className).toContain('focused');
    });
});

选项2:

describe('when the dropdown is open and the user presses the "UP" key', () => {
    it('should focus the first available preceeding option', () => {
        const combobox = fixture.componentInstance;
        combobox.isDropdownOpen = true;
        combobox.focusedIndex = 2;

        input.triggerEventHandler('keydown', { key: 'ArrowUp' });
        fixture.detectChanges();

        expect(combobox.focusedIndex).toBe(1);
    });
});

这两种选择都不对。在第一种情况下,我对行为的假设不是测试本身的一部分 - 即点击&#34;切换&#34;按钮将打开下拉列表,并按下&#34; ArrowDown&#34;键将关注列表中的下一个选项。

在第二种情况下,我访问的属性不属于组件的公共接口(@Inputs和@Outputs),测试本身需要有关实际实现的详细知识。

我该如何处理?

0 个答案:

没有答案