我一直在尝试找出如何使用MatSort正确测试我的表格(使用mat-table)。在ng serve中排序表格可以正常工作,我也能够单击其中一个列的排序按钮,但是在我的测试中,我点击按钮后没有看到表格发生变化。如果有建议或帮助,将不胜感激!
表格组件的代码片段:
表格组件的代码片段:
import { MatSort } from '@angular/material/sort';
export class tablecomponent implements OnInit, AfterViewInit{
@ViewChild(MatSort, {static: true}) sort: MatSort;
ngOnInit(){
this.source = new MatTableDataSource(this.list);
this.source.sort = this.sort;
}
}
snippet of table.component.html
<table mat-table matSort [dataSource]="source">
<ng-container matColumnDef="column_a"
<th mat-header-cell *matHeaderCellDef mat-sort-header>column a</th>
<td mat-cell></td>
</table>
table-component.spec.ts代码片段:
import { async, ComponentFixture, TestBed, inject } from '@angular/core/testing';
import { MatTableModule, MatTableDataSource, MatTable } from '@angular/material/table';
import { tableComponent } from './table.component';
import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import {MatCheckboxModule} from '@angular/material/checkbox';
import {MatToolbarModule} from '@angular/material/toolbar';
import {MatCardModule} from '@angular/material/card';
import { By } from '@angular/platform-browser';
import { MatSortModule, MatSortHeader, Sort, MatSort, SortDirection, MatSortHeaderIntl } from '@angular/material/sort';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { CdkTableModule } from '@angular/cdk/table';
describe('CtableComponent', () => {
let component: tableComponent;
let fixture: ComponentFixture<tableComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ tableComponent],
imports : [
MatTableModule,
MatCheckboxModule,
MatToolbarModule,
MatCardModule,
MatSortModule,
CdkTableModule,
BrowserAnimationsModule
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(tableComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should show a sorted table', async(() => {
component.ngOnInit();
const compiled = fixture.debugElement.nativeElement;
const table = compiled.querySelector('table');
const button = compiled.querySelectorAll('button.mat-sort-header-button');
component.list = TABLE_TEST_DATA.list;
component.source = new MatTableDataSource<Con>(component.list);
component.sort = new MatSort();
component.source.sort = component.sort;
fixture.detectChanges();
button[0].click();
}
expect(table.rows[1].cells[0].textContent).toBe("test");
并进行了上述更改^。但是点击后,组件的component.source仍然与排序无关的更改相同。 - undefinedtable.rows[1].cells[0].textContent
,请确保获取一个新的引用,因为在点击按钮排序后顺序已经改变了。你确定当点击button.mat-sort-header-button
时会进行排序吗?运行应用程序时,请使用开发者工具选择此元素,在控制台中输入$0.click()
并观察它进行排序。如果它没有进行排序,那么可能有另一个元素拥有点击监听器。 - undefinedrole='button'
的div,因此这实际上是有效的:const button = compiled.querySelectorAll(div.mat-sort-header-container)
,参考:https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/button_role - undefined