微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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 举报,一经查实,本站将立刻删除。