我正在尝试对Angular Material中的MatTable
进行DOM测试过滤。我有一个名为xxx-table
的组件,其@Input()名为filter
。
此过滤器使用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();
之前被调用,因此未起作用,因此未检测到更改。
交换它们可以解决此问题。