【问题标题】:ag-Grid: How can I access the gridApi from a Unit Test?ag-Grid:如何从单元测试中访问 gridApi?
【发布时间】:2020-03-10 16:19:05
【问题描述】:

我正在尝试对包含对 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

【问题讨论】:

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


【解决方案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();
});

【讨论】:

  • React 的任何代码 sn-p 吗?
  • 这个解决方案对我不起作用。我错过了什么吗?如果我们将使用 component.gridOptions,那么在测试文件中声明 gridOptions 有什么用,其次是什么是已传递的参数。不应该是数据吗?尽管有这些变化,我还是遇到了同样的错误。可以采取任何替代方法吗?谢谢
猜你喜欢
  • 2019-11-15
  • 2017-07-07
  • 2018-03-11
  • 2019-04-12
  • 2021-01-14
  • 2021-12-17
  • 2021-11-09
  • 2021-01-15
  • 2021-04-23
相关资源
最近更新 更多