【问题标题】:MatCheckbox - Angular Material - Unit tests - How to click to select/deselect all linesMatCheckbox - Angular Material - 单元测试 - 如何单击以选择/取消选择所有行
【发布时间】:2018-05-18 22:01:01
【问题描述】:

我在 Angular 5 应用程序中使用 Angular Material 中的 MatCheckboxModule

我有一个包含多行的表格和一个用于选择/取消选择表格中所有行的复选框:

<mat-checkbox [(ngModel)]="selectAll" (change)="toggleAll()">Toggle</mat-checkbox>

组件部分由一个selectAll布尔属性、一个selectedData数组属性和一个toggleAll函数组成。 如果 selectAll 为真,此函数用所有行填充 selectedData 数组,否则将 selectedData 设置为空。

下面是一个组件代码摘录:

export class BookingComponent implements OnInit {

  booking: Booking;
  selectedData: Line[];
  private _selectAll: boolean;

  ngOnInit() {
    this._selectAll = false;
    this.selectedData = [];
    this.getBooking();
  }

  get selectAll(): boolean {
    return this._selectAll;
  }

  set selectAll(newValue: boolean) {
    this._selectAll = newValue;
  }

  toggleAll() {
    for (const line of this.booking.lines) {
      this.selectAll ? this.selectedData.push(line) : this.selectedData = [];
    }
  }
}

此功能有效。但是,我不知道如何测试将填充 selectedData 数组然后将其清空的单击。事实上,在我的以下代码中,数据总是推送到我的数组中,因为 selectAll 属性不是在第二次点击时更改:

it(`should toggle all lines`, async(() => {
    component.ngOnInit();
    const checkbox = fixture.debugElement.nativeElement.querySelector('.select-all-container mat-checkbox label');
    checkbox.click();
    fixture.whenStable().then(() => {
        expect(component.selectedData.length).toEqual(component.booking.briefLines.length);
        checkbox.click();
        fixture.whenStable().then(() => {
            expect(component.selectedData.length).toEqual(0);
        });
    });
}));

你知道如何解决这个问题吗?

谢谢!

【问题讨论】:

    标签: angular unit-testing checkbox angular-material ngmodel


    【解决方案1】:

    我认为是fixture.detectChanges();应该更新 selectAll 属性。试试这个:

    it(`should toggle all lines`, async(() => {
      component.ngOnInit();
      const checkbox = fixture.debugElement.nativeElement.querySelector('.select-all-container mat-checkbox label');
      checkbox.click();
      fixture.detectChanges();
      fixture.whenStable().then(() => {
          expect(component.selectedData.length).toEqual(component.booking.briefLines.length);
          checkbox.click();
          fixture.whenStable().then(() => {
              expect(component.selectedData.length).toEqual(0);
          });
      });
    }));
    

    【讨论】:

      【解决方案2】:

      至少在 Angular 版本 8(可能更早)中,您需要针对内部隐藏的复选框控件:

      const checkbox = fixture.nativeElement.querySelector('.mat-checkbox-input');
      checkbox.click();
      

      【讨论】:

        猜你喜欢
        • 2019-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-03
        • 1970-01-01
        • 2014-05-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多