无法设置未定义的属性“ paginator”-单元测试

时间:2019-11-13 09:06:55

标签: angular angular-material karma-jasmine

我正在Angular中的一个组件上进行单元测试。测试方案是检查页面中是否存在具有类.div-container的div元素。 因此,基本上,我component.ts中的一个变量使用*ngIf来指示该div是否可见。

请在到目前为止的代码下方查看我的代码。

HTML

<div *ngIf="isAdmin">
    <div class='div-container'>
       <table mat-table [dataSource]="dataSource" matSort matSortActive="DisplayName"
        matSortDirection="asc" matSortDisableClear>
        <ng-container matColumnDef="Firstname">
          <th mat-header-cell *matHeaderCellDef mat-sort-header>First Name</th>
          <td mat-cell *matCellDef="let row">
            {{row.Firstname}}
          </td>
        </ng-container>

        <ng-container matColumnDef="Lastname">
          <th mat-header-cell *matHeaderCellDef mat-sort-header>Last Name</th>
          <td mat-cell *matCellDef="let row">{{row.Lastname}}</td>
        </ng-container>

        <ng-container matColumnDef="Gender">
          <th mat-header-cell *matHeaderCellDef mat-sort-header>Gender</th>
          <td mat-cell *matCellDef="let row">{{row.Gender}}</td>
        </ng-container>

        <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
        <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
      </table>
      <mat-paginator [length]="resultsLength" [pageSizeOptions]="[10, 25, 50, 100]" showFirstLastButtons></mat-paginator>
    </div>
</div>

TS

@Component({
    ...
})
export class SampleComponent implements OnInit {
  @ViewChild(MatSort, { static: false }) set matSort(ms: MatSort) {
    if (ms !== undefined) {
      this.sort = ms;
      this.dataSource.sort = this.sort;
    }
  }

  @ViewChild(MatPaginator, { static: false }) set matPaginator(mp: MatPaginator) {
    if (mp !== undefined) {
      this.paginator = mp;
      this.dataSource.paginator = this.paginator;
    }
  }

  ngOnInit() {
    this.names$ = this.dataService.names$
      .pipe(
        tap(names => {
          this.isLoadingResults = false;
          this.resultsLength = names.value.length;

          this.dataSource = new MatTableDataSource(names.value);
        }),
        catchError(this.handleError)
      )
  }
}

SPEC

describe('SampleComponent', () => {
  let component: SampleComponent;
  let fixture: ComponentFixture<SampleComponent>;

    beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [SharedModule,
        MatPaginatorModule,
        MatSortModule,
        BrowserAnimationsModule],
      declarations: [SampleComponent]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(SampleComponent);
    component = fixture.componentInstance;

    paginator = component.matPaginator;
    sort = component.matSort;

    fixture.detectChanges();
  });

  it(`should hide the div container if 'isAdmin' is false`, () => {
    component.isAdmin = false;
    fixture.detectChanges();

    expect(fixture.debugElement.query(By.css('.div-container'))).toBeNull();
  });

  it(`should show the div container if 'isAdmin' is true`, () => {
    component.isAdmin = true;

    fixture.detectChanges();
    expect(fixture.debugElement.query(By.css('.div-container'))).toBeTruthy();
  });
);

很遗憾,由于此错误,我无法通过此测试。

TypeError: Cannot set property 'paginator' of undefined.

希望有人可以指导我如何正确解决此错误。

TIA!

1 个答案:

答案 0 :(得分:0)

您甚至在dataSourcedataSource生成new之前就尝试设置您的dataSource分页器。设置分页器之前,请尝试检查您的@ViewChild(MatPaginator, { static: false }) set matPaginator(mp: MatPaginator) { if (mp !== undefined && this.dataSource) { // <-- should fix your problem this.paginator = mp; this.dataSource.paginator = this.paginator; } } 是否存在。

public MainWindow()
{
    Grid grd = new Grid();
    grd.Margin = new System.Windows.Thickness(10, 10, 10, 0);
    grd.Background = new SolidColorBrush(Colors.White);
    grd.Height = 104;
    grd.VerticalAlignment = System.Windows.VerticalAlignment.Top;
    grd.ColumnDefinitions.Add(new ColumnDefinition());
    grd.ColumnDefinitions.Add(new ColumnDefinition());
    grd.ColumnDefinitions.Add(new ColumnDefinition());

    RowDefinition row = new RowDefinition();
    row.Height = new System.Windows.GridLength(45);
    grd.RowDefinitions.Add(row);

    row = new RowDefinition();
    row.Height = new System.Windows.GridLength(45);
    grd.RowDefinitions.Add(row);

    row = new RowDefinition();
    row.Height = new System.Windows.GridLength(45);
    grd.RowDefinitions.Add(row);
    InitializeComponent();
}