Angular搭配Jest测试时AG-Grid的gridReady方法未被调用问题
AG Grid gridReady 事件单元测试未触发修复方案
触发原因
AG Grid 在 Angular 环境下的初始化是异步流程,gridReady 事件需要等网格 DOM 渲染、内部实例完全构建完成后才会触发。原测试代码仅执行了 1 次变更检测,没有等待 AG Grid 的异步初始化逻辑执行完毕,因此事件未触发,api 和 columnApi 也不会被赋值。
修复方案
方案1:等待组件稳定后二次执行变更检测
在第一次调用 fixture.detectChanges() 触发组件初始化后,调用 await fixture.whenStable() 等待所有异步任务执行完成,再执行一次变更检测即可触发 gridReady 事件,修改后的测试代码如下:
import { TestBed } from "@angular/core/testing"; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from "@angular/platform-browser-dynamic/testing"; import { AppComponent } from "./app.component"; import { FormsModule } from "@angular/forms"; import { AgGridModule } from "ag-grid-angular"; describe('AG Grid', () => { it('calls grid ready', async () => { TestBed.resetTestEnvironment(); TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting()); await TestBed.configureTestingModule({ imports: [ FormsModule, AgGridModule.withComponents([]), ], declarations: [AppComponent] }).compileComponents(); const fixture = TestBed.createComponent(AppComponent); const component = fixture.componentInstance; // 触发组件初始化 fixture.detectChanges(); // 等待AG Grid异步初始化完成 await fixture.whenStable(); // 同步状态触发gridReady事件 fixture.detectChanges(); expect(component.api).toBeDefined(); expect(component.columnApi).toBeDefined(); }); })
方案2:验证gridReady回调函数调用
如果需要确认绑定的gridReady处理函数确实被执行,可以配合Jest的spy功能做断言:
// 假设组件内gridReady绑定的处理函数名为onGridReady const gridReadySpy = jest.spyOn(component, 'onGridReady').and.callThrough(); fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); // 验证回调被调用 expect(gridReadySpy).toHaveBeenCalled(); // 验证回调拿到的api实例正常 expect(gridReadySpy.mock.calls[0][0].api).toBeDefined();
内容的提问来源于stack exchange,提问作者Jöcker
相关产品推荐
相关产品推荐

