angular - 为使用 mat-autocomplete 的组件编写单元测试

标签 angular unit-testing autocomplete angular-material mat-autocomplete

我是 Angular 的新手,我正在尝试使用 Angular 5 构建一个具有自动完成功能的文本字段。

我在 Angular Material docs 中找到了这个例子:

https://stackblitz.com/angular/kopqvokeddbq?file=app%2Fautocomplete-overview-example.ts

我想知道如何编写单元测试来测试自动完成功能。我正在为输入元素设置一个值并触发“输入”事件并尝试选择 mat-option 元素,但发现它们都没有被创建:

我的组件 html 的相关部分:

<form>
  <mat-form-field class="input-with-icon">
    <div>
      <i ngClass="jf jf-search jf-lg md-primary icon"></i>
      <input #nameInput matInput class="input-field-with-icon" placeholder="Type name here"
             type="search" [matAutocomplete]="auto" [formControl]="userFormControl" [value]="inputField">
    </div>
  </mat-form-field>
</form>

<mat-autocomplete #auto="matAutocomplete">
  <mat-option *ngFor="let option of filteredOptions | async" [value]="option.name"
              (onSelectionChange)="onNameSelect(option)">
    {{ option.name }}
  </mat-option>
</mat-autocomplete>

规范文件:

it('should filter users based on input', fakeAsync(() => {
    const hostElement = fixture.nativeElement;

    sendInput('john').then(() => {
        fixture.detectChanges();
        expect(fixture.nativeElement.querySelectorAll('mat-option').length).toBe(1);

        expect(hostElement.textContent).toContain('John Rambo');
    });
}));
function sendInput(text: string) {
    let inputElement: HTMLInputElement;

    inputElement = fixture.nativeElement.querySelector('input');
    inputElement.focus();
    inputElement.value = text;
    inputElement.dispatchEvent(new Event('input'));
    fixture.detectChanges();
    return fixture.whenStable();
}

组件 html:

userFormControl: FormControl = new FormControl();

ngOnInit() {
    this.filteredOptions = this.userFormControl.valueChanges
        .pipe(
            startWith(''),
            map(val => this.filter(val))
        );
}

filter(val: string): User[] {
    if (val.length >= 3) {
        console.log(' in filter');
        return this.users.filter(user =>
            user.name.toLowerCase().includes(val.toLowerCase()));
    }
}

在此之前,我意识到要让 FormControl 对象设置值,我必须先执行 inputElement.focus(),这与使用 Angular Material 的垫输入有关。我必须做些什么才能触发打开 mat-options Pane 吗?

如何使这个测试起作用?

最佳答案

@Adam对先前回答的评论让我想到了 mat-autocomplete component's own test , 特别 here .哪里可以看到focusin是打开“选项”的事件。

但它们实际上在组件外部的覆盖层中打开,所以在我的测试中 fixture.nativeElement.querySelectorAll('mat-option').length0 但如果我查询元素 document.querySelectorAll('mat-option') 我得到了预期数量的选项。

总结一下:

    fixture.detectChanges();
    const inputElement = fixture.debugElement.query(By.css('input')); // Returns DebugElement
    inputElement.nativeElement.dispatchEvent(new Event('focusin'));
    inputElement.nativeElement.value = text;
    inputElement.nativeElement.dispatchEvent(new Event('input'));

    fixture.detectChanges();
    await fixture.whenStable();
    fixture.detectChanges();

    const matOptions = document.querySelectorAll('mat-option');
    expect(matOptions.length).toBe(3,
      'Expect to have less options after input text and filter');

额外的球:如果你想点击一个选项(我点击了)你可以继续这样:

    const optionToClick = matOptions[0] as HTMLElement;
    optionToClick.click();
    fixture.detectChanges();

虽然我没有成功点击并将值输入到输入中。 🤨 好吧,我不是专家测试人员,但可能该行为应该包含在自己的 mat-autocomplete 测试中(实际上是)并依赖它?

关于angular - 为使用 mat-autocomplete 的组件编写单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50431894/

相关文章:

angular - Ionic 2 中的谷歌字体

javascript - 功能策略已在本文档中禁用地理定位

javascript - Angular - 带参数的方法的 Jest 单元测试

unit-testing - 你如何从 Rhino.Commons 模拟 UnitOfWork?

javascript - 选择并按 Enter 键时自动完成 jQueryUI 双重调用功能

Netbeans 中的自动完成

javascript - Angular 5 httpClient 和 promise

angular - 找不到模块“@ google/ map ”

c# - 如何在 Controller 中模拟 Automapper (IMapper)

jQuery 自动完成 ajax 类型错误