角单元测试未初始化Ag-Grid

时间:2020-03-17 21:02:02

标签: angular typescript unit-testing ag-grid

我正在尝试对包含ag-Grid的组件进行单元测试,但是从未调用onGridReady函数,因此所有涉及ag-Grid的测试均失败。在测试运行之前,如何使onGridReady真正被调用?

规格文件:

describe('MyComponent', () => {
  let spectator: SpectatorHost<MyComponent>;
  let fixture: ComponentFixture<MyComponent>;

  const createHost = createHostFactory({
    component: MyComponent,
    entryComponents: [MyComponent],
    imports: [
      TranslateModule.forRoot(),
      AgGridModule.withComponents([]),
      MatTooltipModule,
      InlineSVGModule.forRoot(),
      MaterialModule,
      HMSharedModule,
    ],
    providers: [
      {
        provide: MatDialogRef,
        useValue: [],
      },
      {
        provide: MAT_DIALOG_DATA,
        useValue: [],
      },
      HttpClient,
      HttpHandler,
    ],
  });

  beforeEach(() => {
    spectator = createHost(`<MyComponentSelector></MyComponentSelector>`, {
      hostProps: {},
    });
    fixture = spectator.fixture;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(spectator.component).toBeTruthy();
  });

  it('should detect changes', () => {
    spectator.fixture.detectChanges();

  });

“应创建”有效,但“应检测到更改”因以下错误而失败:

TypeError: Cannot read property 'setColumnDefs' of undefined

在html中,这是我的ag-grid:

          <ag-grid-angular
            style="height: 157px"
            #agGrid1
            class="ag-grid ag-theme-balham"
            [rowSelection]="rowSelection"
            [columnDefs]="columnDefs1"
            [gridOptions]="gridOptions"
            (gridReady)="onGridReady($event)"
            (gridSizeChanged)="resizeColumns($event)"
            (cellValueChanged)="updateBottomGrid('agGrid1', false)"
            [singleClickEdit]="true"
          >
          </ag-grid-angular>

这是onGridReady:

  onGridReady(params: any): void {
    console.log('onGridReady called successfully');
    if (this.agGrid1) {
      this.agGrid1.api = params.api;
    }
  }

从不打印控制台语句,因此永远不会调用onGridReady。如何在单元测试前调用它?

编辑:有人提到我需要为columnDefs提供数据,但是我已经有了initializeColumnDefs()来定义所有列,并且我已经确认在单元测试期间确实会调用它,所以这不是问题

此外,我认为这无关紧要,但是该组件是MatDialog。

2 个答案:

答案 0 :(得分:2)

我可以通过添加以下内容来消除此错误:

import { ClientSideRowModelModule } from '@ag-grid-community/client-side-row-model';

modules: Module[] = [ClientSideRowModelModule];

并将模块添加到网格中

          <ag-grid-angular
            style="height: 157px"
            #agGrid1
            class="ag-grid ag-theme-balham"
            [rowSelection]="rowSelection"
            [columnDefs]="columnDefs1"
            [gridOptions]="gridOptions"
            (gridReady)="onGridReady($event)"
            (gridSizeChanged)="resizeColumns($event)"
            (cellValueChanged)="updateBottomGrid('agGrid1', false)"
            [singleClickEdit]="true"
            [modules]="modules"
          >
          </ag-grid-angular>

我不知道为什么要修复它。

答案 1 :(得分:0)

以下是有关如何使用模块的文档:https://www.ag-grid.com/javascript-grid-modules/。您需要注册要使用的模块,才能使Ag-grid正常工作。