【发布时间】:2020-06-28 23:51:05
【问题描述】:
我正在尝试对包含 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。
【问题讨论】:
-
好吧,抛出的错误表明您正在尝试在未定义/未初始化的变量上使用
setColumnDefs。如果您提供更多代码会很有帮助。 +您可能需要设置模拟变量以使变更检测正常工作 -
@lietutis "setColumnDefs" 不在我的代码中。 ag-grid api 是未定义的,因为它只能由未调用的 onGridReady 定义。
-
hm,您应该查看
ag-grid生命周期,我认为问题在于您需要为 columnDefs 或其他单向绑定提供数据:?这就是为什么你没有得到控制台日志的原因,因为它之前失败了
标签: angular typescript unit-testing ag-grid