【问题标题】:Angular Material - testing MatPaginatorAngular Material - 测试 MatPaginator
【发布时间】:2018-03-30 07:39:09
【问题描述】:

当我尝试测试为 Angular Material 中的 MatPaginator 设置值的组件方法时,我收到此错误:

TypeError: Cannot set property 'pageIndex' of undefined

这是我的代码:

组件:

resetVacancySearch = () => {
    this.isVacanciesSearchMode = false;
    this.searchVacanciesValue = '';
    this.paginatorVacancies.pageIndex = 0; // reset to the first page
    this.paginatorVacancies.pageSize = 10;
    this.getVacanciesList(0, 10, 'name', 'ASC');
}

测试文件:

it('should call sourcingService.getVacanciesList and reset the search value from the input field', () => {
        spyOn(sourcingService, 'getVacanciesList').and.returnValue(Observable.of());
        component.resetVacancySearch();
        expect(sourcingService.getVacanciesList).toHaveBeenCalledWith(0, 10, 'name', 'ASC');
        expect(component.searchVacanciesValue).toEqual('');
 });

应用程序运行良好,但我无法将 MatPaginator 的实例放入测试文件。有人可以建议我如何将 MatPaginator 模拟到测试中吗?谢谢!

【问题讨论】:

  • 你弄明白了吗?
  • 你能提供这个问题的解决方案吗?

标签: angular jasmine angular-material


【解决方案1】:

只需添加

MatPaginatorModule,
BrowserAnimationsModule

在 import[] 数组中。

【讨论】:

    【解决方案2】:

    我能够访问在测试类的组件中定义的分页器。

    在component.ts中,我添加了这一行来访问分页器

    @ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;

    component.html

    <div>
      <mat-paginator [pageSizeOptions]="pageSizeOptions" (page)="onPageChange($event)">
      </mat-paginator>
    </div>
    

    在component.spec.ts中,

    beforeEach(async(() => {TestBed.configureTestingModule({
      declarations: [DiscoverAddTargetDialogComponent],
      imports: [NoopAnimationsModule,MatTableModule, MatSortModule, MatPaginatorModule],
      providers: []
    })
      .compileComponents();}));
    

    我访问分页器如下:

    console.log("length :" + component.paginator.length);

    【讨论】:

      猜你喜欢
      • 2020-05-08
      • 2020-06-09
      • 2021-03-13
      • 2019-10-07
      • 2020-11-23
      • 2018-08-01
      • 2018-10-12
      • 2021-04-23
      • 2019-01-17
      相关资源
      最近更新 更多