0

我有一个使用 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 吗?我该怎么做?

4

0 回答 0