[英]Angular material table filter testing
I'm trying to DOM test filtering of MatTable
in Angular Material.我正在尝试对 Angular Material 中的
MatTable
进行 DOM 测试过滤。 I have a component named xxx-table
, with an @Input() named filter
.我有一个名为
xxx-table
的组件,带有一个名为filter
的 @Input() 。
This filter is copied into dataSource.filter
using onNgChanges, like this:使用 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;
}
It is working fine in the UI, so I'm trying to DOM test it using
fixture
.它在 UI 中运行良好,所以我正在尝试使用
fixture
对它进行 DOM 测试。 It seems like it's not updating the DOM in real time.似乎它没有实时更新 DOM。 I tried like this:
我试过这样:
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');
});
});
For fixture.whenStable to work you need to wrap your test in async:为了让 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');
});
}));
I'm not exactly sure that's the problem, but I would try that.我不确定那是问题所在,但我会尝试这样做。
So, for future reference, it wasn't working because fixture.detectChanges();
因此,为了将来参考,它不起作用,因为
fixture.detectChanges();
is called before component.ngOnChanges();
在
component.ngOnChanges();
之前调用component.ngOnChanges();
, so the changes were not detected. ,因此未检测到更改。
Swapping them fixes the issue.交换它们可以解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.