首页 > 解决方案 > 为过滤客户的 mat-autocomplete 编写单元测试

问题描述

我正在为 Angular 应用程序编写单元测试,确切地说是 angular6。我在代码中有 mat-autocomplete,我想要测试的只是用户根据我在输入框中输入的内容进行过滤。我受到帖子的启发,请在此处输入链接描述

这是spec文件的代码片段

  it('should filter customer',async () => {
    fixture.detectChanges();
    let toggleButton = fixture.debugElement.query(By.css('input'));
    console.log(toggleButton.nativeElement);

    toggleButton.nativeElement.dispatchEvent(new Event('focusin'));
    toggleButton.nativeElement.value = "xyz";
    toggleButton.nativeElement.dispatchEvent(new Event('input'));
    fixture.detectChanges();
    await fixture.whenStable();
    fixture.detectChanges();

    const matOptions = document.querySelectorAll('mat-option');
    expect(matOptions.length).toBe(1); //test fails

  })


  <mat-form-field >
     <input id="inputCustomer" matInput [matAutocomplete]="auto"  [formControl]="customerFilterControl">
     <mat-autocomplete panelWidth ="450px" #auto="matAutocomplete" [displayWith] = "displayFn" style="width:750px;">
         <mat-option  *ngFor="let customer of filteredOptions | async" [value] ="customer.AccountID + '('+ customer.AccountName + ')'" (onSelectionChange)="onCustomerChange(customer)">
         {{customer.AccountID}} ({{customer.AccountName}})
        </mat-option>
     </mat-autocomplete>
  </mat-form-field>

**typescript.ts**
    this.filteredOptions = this.customerFilterControl.valueChanges.pipe(
      startWith(''),
      map(value => this._filter(value))
    );  


  _filter(value:any):any[] {
    const filterValue = value.toLowerCase();
    return this.customers.filter(function (option) {
      if(option.AccountID.includes(filterValue) || option.AccountName.includes(filterValue)) {
        return option;
       }
    });
  }

在此处输入图像描述

标签: angulartypescriptunit-testing

解决方案


您似乎缺少初始化选项

  it('should filter customer',async () => {
    // Prepare the data
    const option1 = {AccountID: 1, AccountName: 'AccountName1'};
    const option2 = {AccountID: 2, AccountName: 'xyz'}
    // Prepare the data source
    fixture.component.filteredOptions = of([option1,option2])
    fixture.detectChanges();
    let toggleButton = let toggleButton = fixture.debugElement.query(By.css('#inputCustomer'));
    console.log(toggleButton.nativeElement);

    toggleButton.nativeElement.dispatchEvent(new Event('focusin'));
    toggleButton.nativeElement.value = "xyz";
    toggleButton.nativeElement.dispatchEvent(new Event('input'));
    fixture.detectChanges();
    await fixture.whenStable();
    fixture.component._filter("xyz");
    fixture.detectChanges();

    const matOptions = document.querySelectorAll('mat-option');
    expect(matOptions.length).toBe(1); //test fails

  })

这样,当您添加自动完成值时,您的组件将有一些值可供选择。

请记住,您应该使用 of 运算符(让我知道它是否有效,因为我没有测试过它)才能使异步管道工作。


推荐阅读