【发布时间】:2020-04-30 21:16:51
【问题描述】:
我一直致力于构建一个 Angular 应用程序。它由一个带有分页、排序和过滤的表格组成。
运行ng serve 时一切正常,但运行ng test 时分页不起作用。
我想为分页器编写测试用例,但datasource.paginator.length 给我 0 即使数据源有数据。
下面是分页器在测试运行中没有绑定的截图。
下面是我的代码sn-p:
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 需要几个参数作为构造函数,这会导致另一个问题。
请帮助我理解为什么分页不起作用。 提前致谢! :)
【问题讨论】:
标签: angular unit-testing pagination karma-jasmine paginator