繁体   English   中英

角料台过滤器测试

[英]Angular material table filter testing

我正在尝试对 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');
    });
  });

为了让 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');
    });
  }));

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

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

交换它们可以解决问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM