【发布时间】: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');
});
});
【问题讨论】:
-
第一种测试方式来自:github.com/angular/components/blob/…我尝试在测试前等待1000ms,但似乎没有任何改变。
标签: angular unit-testing dom angular-material