angular - ag-grid API 在 Angular 单元测试中未定义

标签 angular unit-testing ag-grid ag-grid-angular

我正在用 Angular 编写 Ag-grid 的单元测试用例。

test.component.ts:

public gridApi: GridApi; 
public gridColumnApi;

constructor(private service: Service) {
 this.initializeAgGrid(); // this method just initializing the grid
}

ngOnInit(): void {
 this.setHraDashboardData();
}

onGridReady(params) {
 this.gridApi = params.api;
 this.gridColumnApi = params.columnApi;
 this.gridApi.sizeColumnsToFit();
}

setHraDashboardData() {
 this.service.getData(1).then((data) => {
   this.uiData = data;
   this.rowData = this.generateRowData(this.data); // this method writing some logic for UI
   this.gridApi.setRowData(this.rowData);
 });
}

test.component.spec.ts

beforeEach(() => {
  fixture = TestBed.createComponent(HraFormComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
});

it('grid API is available after `detectChanges`', async() => {
  await fixture.whenStable().then(()=>{
    fixture.detectChanges();
    const elm = fixture.debugElement.nativeElement;
    const grid = elm.querySelector('#Grid');
    const firstRowCells = grid.querySelectorAll('div[row-id="0"] div.ag-cell-value');
    const values = Array.from(firstRowCells).map((cell: any) => cell.textContent.trim());

    // assert
    expect(component.rowData[0].title).toEqual(values[0]);
  });
});

现在上述测试用例由于component.gridApi而失败是 undefined ,因此无法为网格 this.gridApi.setRowData(this.rowData) 分配值.

最佳答案

在编写涉及 ag-grid api 可用性的单元测试时,在这种情况下有两件事可以帮助您:

您可以尝试使用 this.gridOptions.api (this.gridOptions.api.setRowData ...),而不是等待 gridReady 事件,因为大多数情况通常,它会更快初始化(在 onGridReady 触发之前)

您可以结合使用settimeout来做到这一点函数也是如此,当我过去遇到与您类似的问题时,我多次使用了该函数:

而不是:

this.gridApi.setRowData(this.rowData);

尝试:

setTimeout(() => { this.gridApi.setRowData(this.rowData);}, 100);

您可以增加 settimeout 的时间到 200、300、500 或更多,对我来说,大多数时候只需使用非常小的数字(10 毫秒)的 settimeout 即可。

settimeout这不是一个理想的解决方案,但在许多情况下都有效。第一个选项应该更干净,您甚至可以添加超时以使其正常工作。

使用 fakeAsync zone 而不是 async 也会有所帮助。

关于angular - ag-grid API 在 Angular 单元测试中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65449177/

相关文章:

angular - 如何在没有嵌入式订阅的情况下一个接一个地执行异步操作

java - 如何在 java 中测试客户端管道?

python - 如何使用 Mock 库修补 Python 类

angular - ag-grid : GroupByColum Sort not working for numeric values, 只提供字符串排序

angular - 如何在 Angular 2 中将模态作为单独的组件制作?

angular - TypeError : Cannot read property 'taxTypeId' of undefined at Object. View_FullEditTaxComponent_0._co [as updateDirectives]

javascript - Angular 4 如何在路由时更改 URL,而不出现 "#"并且没有副作用?

android - 如何在 Mockito3.x 中使用 PowerMock?

Ag-grid:计算每个过滤器选择的行数

reactjs - AG-Grid 与 Redux