angular - 如何测试网格 API 是否可用于 Angular 中的 ag-grid?
问题描述
我试图使用 jasmine 为 ag-grid 编写单元测试。
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>
.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; } }
规格
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)
解决方案
对于这种情况(不知道 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();
});
我记得当我使用AgGrid
Angular 单元测试时,我不得不使用waitUntil
很多。如果该测试超时(等待无法解决),那么我认为测试设置有问题。
推荐阅读
- sql - 如何将唯一键(列中的唯一值与另一列中的值)复制到多次出现的记录中?
- python - 熊猫中列的唯一对
- c# - 图像在C#的pictureBox中消失
- arrays - 从用户表记录中返回所有值
- c# - Azure Functions .Net5 流式响应 C#
- css - LineHeight 在 ios 和 android 和 web 上表现不同
- python - 为什么 Python 解释器在使用 Pyomo 调用 CBC 求解器后关闭,尽管没有引发错误?
- apache-spark - Databricks 社区版集群无法启动
- ruby-on-rails - 彪马。是否可以获得当前正在运行的请求
- c# - 如何在 C# 中以相同的方法处理数字和可为空的数字变量