问题描述
有人在Angular 2中对ag-grid组件进行单元测试吗?
Has someone worked on unit testing ag-grid components in Angular 2?
对我来说,在运行测试用例时,this.gridOptions.api仍未定义.
For me, this.gridOptions.api remains undefined when the test cases run.
推荐答案
很抱歉聚会晚了一点,但几天前我一直在寻找答案,所以想把答案留给其他人到此为止.如上面的Minh所述,必须运行现代等效的 $ digest
才能使Ag-grid api可用.
Sorry to be a little late to the party but I was looking for an answer to this just a couple of days ago so wanted to leave an answer for anyone else that ends up here. As mentioned by Minh above, the modern equivalent of $digest
does need to be run in order for ag-grid api's to be available.
这是因为在运行 onGridReady()
后,您可以通过参数访问api,如下所示.当带有网格的组件正在初始化时,它将自动运行.假设它在网格(gridReady)=" onGridReady($ event)"
This is because after the onGridReady()
has run you have access to the api's via the parameter, looking like so. This is run automatically when a component with a grid is initialising. Providing it is defined in the grid (gridReady)="onGridReady($event)"
public onGridReady(params)
{
this.gridOptions = params;
}
这现在意味着您可以访问 this.gridOptions.api
并已被定义,您需要通过运行 detectChanges()
在测试中重新创建它.这就是我在项目中使用它的方式.
This now means you could access this.gridOptions.api
and it would be defined, you need to re-create this in your test by running detectChanges()
. Here is how I got it working for my project.
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges(); // This will ensure the onGridReady(); is called
这反过来会导致在运行测试时定义 .api
.这是Angular 6.
This should inturn result in .api
being defined when running tests. This was Angular 6.
有时测试可能必须执行等待或滴答声:
Occasionally the test may have to perform an await or a tick:
it('should test the grid', fakeAsync( async () => {
// also try tick(ms) if a lot of data is being tested
// try to keep test rows as short as possible
// this line seems essential at times for onGridReady to be processed.
await fixture.whenStable();
// perform your expects...after the await
}));
这篇关于Angular 2中的单元测试农业网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!