ag-Grid:如何从单元测试访问gridApi?

时间:2019-11-14 16:19:17

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

我正在尝试对包含对gridApi的调用的函数进行单元测试,例如this.gridApi.getSelectedRows();。当单元测试到达这一行时,它会出现此错误:Failed: Cannot read property 'getSelectedRows' of undefined,因为尚未定义gridApi。

如何从单元测试中定义gridApi?通常在onGridReady函数中定义如下:

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

是否可以从单元测试中触发onGridReady?我不知道可以向其发送什么参数。还有其他方法来定义this.gridApi吗?

1 个答案:

答案 0 :(得分:1)

this.gridApi和this.gridColumnApi在测试用例中自动初始化。为此,需要从“ ag-grid-angular”导入AgGridModule。 并初始化组件与下面的代码相同:

let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;

beforeEach(async(() => {
    TestBed.configureTestingModule({
        declarations: [MyComponent],
        imports: [
            AgGridModule.withComponents([])
        ]
    }).compileComponents();

    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
}));

要在文件顶部测试onGridReady导入。

import { GridOptions } from "ag-grid-community";

并声明一个变量

gridOptions: GridOptions = <GridOptions>{};

编写测试用例

it('onGridReady called', () => {
const data = {
    api: component.gridOptions.api,
    columnApi: component.gridOptions.columnApi
}
component.onGridReady(params);
expect(component.gridApi).not.toBeNull();
expect(component.gridColumnApi).not.toBeNull();
});