【问题标题】:Angular material table filter testing角料表过滤器测试
【发布时间】:2019-12-17 15:39:30
【问题描述】:

我正在尝试对 Angular Material 中的 MatTable 进行 DOM 测试过滤。我有一个名为xxx-table 的组件,其中有一个名为filter 的@Input()。

使用 onNgChanges 将这个过滤器复制到 dataSource.filter,如下所示:

export class XXXTableComponent implements OnInit, OnChanges {
    @Input()
    loadedDatas: Item[];

    @Input()
    filter: string = '';

  dataSource: MatTableDataSource<Suppressed>;

  @ViewChild(MatSort) sort: MatSort;

  ngOnInit(): void {
    this.dataSource = new MatTableDataSource(this.suppressedDevices);
    this.dataSource.sort = this.sort;
  }

    ngOnChanges(): void {
        if(this.dataSource) this.dataSource.filter = this.filter;
    }

它在 UI 中运行良好,所以我尝试使用fixture 对其进行 DOM 测试。 似乎它没有实时更新 DOM。我试过这样:

  it('should filter the dataSource', () => {
    expect.hasAssertions();
    component.filter = 'New York';
    fixture.detectChanges();
    component.ngOnChanges();

    expect(component.dataSource.filter).toBe('New York');
    expect(component.dataSource.filteredData.length).toBe(1);

    expect(component.dataSource.filteredData[0].address).toBe(
      '43, Highway Road, 23413'
    );

    // Why isn't that passing?
    return fixture.whenStable().then(() => {
      const rows = fixture.nativeElement.querySelectorAll('tbody tr');

      expect(rows.length).toBe(1); // Fails here
      const cell = fixture.nativeElement
        .querySelector('tbody td:nth-child(3)')
            expect(cell.textContent)
        .toBe('43, Highway Road, 23413');
    });
  });

【问题讨论】:

标签: angular unit-testing dom angular-material


【解决方案1】:

为了让 fixture.whenStable 工作,您需要将测试包装在异步中:

  it('should filter the dataSource', async(() => {
    expect.hasAssertions();
    component.filter = 'New York';
    fixture.detectChanges();
    component.ngOnChanges();

    expect(component.dataSource.filter).toBe('New York');
    expect(component.dataSource.filteredData.length).toBe(1);

    expect(component.dataSource.filteredData[0].address).toBe(
      '43, Highway Road, 23413'
    );

    // Why isn't that passing?
    return fixture.whenStable().then(() => {
      const rows = fixture.nativeElement.querySelectorAll('tbody tr');

      expect(rows.length).toBe(1); // Fails here
      const cell = fixture.nativeElement
        .querySelector('tbody td:nth-child(3)')
            expect(cell.textContent)
        .toBe('43, Highway Road, 23413');
    });
  }));

我不确定这是问题所在,但我会尝试。

【讨论】:

  • 不错的尝试,但我的同事找到了解决方案:)
【解决方案2】:

因此,为了将来参考,它不起作用,因为在 component.ngOnChanges(); 之前调用了 fixture.detectChanges();,因此未检测到更改。

交换它们可以解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 2018-10-01
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    相关资源
    最近更新 更多