[英]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.