首页 > 解决方案 > 如何测试网格 API 是否可用于 Angular 中的 ag-grid?

问题描述

我试图使用 jasmine 为 ag-grid 编写单元测试。

  1. html

     <ag-grid-angular
     style="width: 500px; height: 400px;"
     class="ag-theme-alpine"
     [rowData]="rowData"
     [columnDefs]="columnDefs"
     rowSelection='single'
     (gridReady)="onGridReady($event)"
     >
     </ag-grid-angular>
    
  2. .ts

     import { Component, Input, OnInit } from '@angular/core';
     import { ColDef } from 'ag-grid-community';
     import { DataGrid } from 'src/app/shared/models/datagrid.model';
     @Component({
     selector: 'app-simple-view',
     templateUrl: './simple-view.component.html',
     styleUrls: ['./simple-view.component.scss']
     })
     export class SimpleViewComponent implements OnInit {
     @Input('data') data: any | undefined;
    
     columnDefs: ColDef[] = [
     { field: 'Geography', sortable: true },
     { field: 'Category', sortable: true },
     { field: 'DataType', sortable: true }
    ];
    
    rowData: DataGrid[] | undefined;
    
    public gridApi: any;
    
    constructor() { }
    
    ngOnInit(): void {
     this.rowData = this.data;
    }
    
    onGridReady(params: any) {
     this.gridApi = params.api;
    
    }
    }
    
  3. 规格

     it('grid API is available after `detectChanges`', () => {
     fixture.detectChanges();
     expect(component.gridOptions.api).toBeTruthy();
     });
    

此测试方法失败并出现以下错误

SimpleViewComponent > grid API 在detectChanges Expected undefined 为真后可用。错误:预期未定义是真实的。在用户上下文。(http://localhost:9876/karma_webpack/ webpack :/src/app/features/overview/components/simple-view/simple-view.component.spec.ts:45: 31) 在 Generator.next () at asyncGeneratorStep (http://localhost:9876/karma_webpack/ webpack :/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:3: 1)

标签: angularjasmineag-grid

解决方案


对于这种情况(不知道 AGGrid 何时会解决它将解决的问题),我喜欢使用waitUntil实用程序函数。

// Put this in a utils section of the project with the name of waitUntil.ts
// This function will keep retrying and wait until the function is truthy
// before proceeding

import { interval } from 'rxjs';
.....
export const waitUntil = async (untilTruthy: Function): Promise<boolean> => {
  while (!untilTruthy()) {
    await interval(25).pipe(take(1)).toPromise();
  }
  return Promise.resolve(true);
};
// Use waitUntil with async await

it('grid API is available after `detectChanges`', async () => {
   fixture.detectChanges();
   // wait until gridOptions.api is truthy
   await waitUntil(() => !!component.gridOptions.api);
   expect(component.gridOptions.api).toBeTruthy();
 });

我记得当我使用AgGridAngular 单元测试时,我不得不使用waitUntil很多。如果该测试超时(等待无法解决),那么我认为测试设置有问题。


推荐阅读