我一直在构建Angular应用。它由具有分页,排序和过滤功能的表组成。运行ng serve
时一切正常,但是运行ng test
时分页不起作用。我想为分页器编写测试用例,但是即使数据源中有数据,datasource.paginator.length
也给我0。
下面是截屏程序在测试运行中未绑定的屏幕截图。
下面是我的代码段:
app.component.ts
public weatherData : Array<CityWeather>;
@ViewChild(GraphComponent) graphComponent : GraphComponent;
/**
* Table related variables
*/
displayedColumns: string[] = ['id', 'city_name', 'country', 'temperature', 'feels_like', 'humidity', 'weather_description'];
public dataSource : MatTableDataSource<any>;
@ViewChild(MatSort, {static: true}) sort: MatSort;
@ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;
constructor(private weatherService: WeatherService) {}
ngOnInit() {
this.weatherService.getWeather(cityIds)
.subscribe(data => {
this.weatherData = this.extractCityWeather(data);
this.dataSource = new MatTableDataSource(this.weatherData);
this.dataSource.sort = this.sort;
this.dataSource.paginator = this.paginator;
}
);
}
app.component.spec.ts
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent,
GraphComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
HttpClientModule,
MaterialModule
],
providers: [
{
provide: WeatherService,
useClass: WeatherServiceMock
},
MatPaginator,
MatSort
],
schemas: [ NO_ERRORS_SCHEMA ]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
component.graphComponent = new GraphComponentMock();
component.ngOnInit();
fixture.detectChanges();
});
it('should create the app', () => {
expect(component).toBeTruthy();
});
it('should populate datasource', () => {
expect(component.dataSource).not.toBeNull();
})
/**
* Filtering test case
*/
it('city filter should filter out 1 city', () => {
component.applyFilter('cam');
expect(component.dataSource.filteredData.length).toEqual(1);
})
it('city filter should not filter anything', () => {
component.applyFilter('RANDOM_CITY_NAME_ALSKJDLASKJ');
expect(component.dataSource.filteredData.length).toEqual(0);
})
it('pagination should work', () => {
let i=1;
while(component.dataSource.paginator.hasNextPage()) {
i++;
component.dataSource.paginator.nextPage();
}
expect(i).toEqual(4);
})
});
@ViewChild(MatPaginator, {static: true}) paginator: MatPaginator
这里使用static:true
,因为如果将其删除,我将不得不在测试运行中模拟该对象。 MatPaginator期望作为构造函数的几个参数导致另一个问题。
[请帮助我了解为什么分页不起作用。提前致谢! :)
我将fixture.detectChanges();
更改为fixture.autoDetectChanges();
,事情开始起作用。