我正在尝试对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');
});
});
答案 0 :(得分:1)
要使fixture.when稳定工作,您需要将测试包装在异步中:
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');
});
}));
我不确定这是问题所在,但我会尝试的。
答案 1 :(得分:0)
因此,由于fixture.detectChanges();
在component.ngOnChanges();
之前被调用,因此无法使用,以供将来参考。
交换它们可以解决此问题。