Angular 打字稿 TypeError:无法读取未定义的属性“setDomLayout” - 使用 ag-grid 测试组件

问题描述

我有一个使用 ag-grid 的组件。

@Component({
  selector: 'app-summary',templateUrl: './summary.component.html',styleUrls: ['./summary.component.scss']
})
export class SummaryComponent implements OnInit {
  IsChecked: boolean = false;
  rowData: Array<any>;
  errorMessage: any =  null;
  summaryData: Array<Summary>;
  defaultColWidth: number = 200;
  numberColWidth: number = 120;
  defaultColDef: any;
  innerHeight: any;
  private gridApi;
  gridOptions: GridOptions;
  pivotMode: boolean;
  
  ngOnInit(): void {
    this.pivotMode = false;
    this.gridOptions = this.agGridServ.getDefaultGridOptions();
    
  }
  
  onGridReady(params) {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;    
  }
  
  handleUserSelection(selection) {
    ..
    ..
    this.getSummaryData(requestObject);   
    ..
    ..
    
  }
  getSummaryData(selections: any): void {
    this.summaryData = [];
    this.errorMessage = null;
    this.gridApi.setDomLayout('normal');
    this.summaryService.getSummaryViewData(
       selections
    )
    .subscribe (
    .
    .
    )
  }
}

当我运行此方法的测试时,它失败了。

describe('SummaryComponent',() => {

  let spectator: spectator<SummaryComponent>;

  let selection: any = {
    selectedDateFrom: {year: 2020,month: 5,day: 29},selectedDateto: {year: 2020,month: 6,day: 30},}
  
  const createComponent = createComponentFactory({
    component: SummaryComponent,declarations: [],imports: [HttpClientTestingModule,MatSnackBarModule,RouterTestingModule,AgGridModule.withComponents([])
             ],providers: [
      { provide: MatDialog,useClass: MatDialogMock },],schemas: [NO_ERRORS_SCHEMA],mocks: [BasicAuthService,RefdataService,SummaryDataService,detectChanges: false
  });
  
  beforeEach(()=> {
    spectator= createComponent();
    
  });
  
  it('should handle user selection',() => {    
    jest.spyOn(spectator.component.refData,'getReferenceData').mockReturnValue(of(refDataSample));
    spectator.detectChanges();
    spectator.component.handleUserSelection(selection);
    expect(spectator.component.handleUserSelection).toBeTruthy();
  });
}

以下是我运行测试时的错误。我尝试使用检测更改(假设 gridapi 应该初始化),但它没有帮助? 我们甚至可以在测试中跳过这一行吗?即模拟(仅 gridapi 行)?

 TypeError: Cannot read property 'setDomLayout' of undefined

   560 |     this.expandedState = [];
 > 561 |     this.gridApi.setDomLayout('normal');
       |   

组件(已测试)的 gridAPi 未定义。我该如何解决这个问题?

更新:

请注意,我不想测试 ag grid api,我的组件(我正在测试)有一个方法(我正在测试)调用

this.gridApi.setDomLayout('normal');

说 gridApi 未定义是失败的。我正在寻找解决错误方法,因为我的测试与查看 gridApi 工作无关。所以我可以在测试中模拟 gridApi 吗?我该怎么做?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)