Unit testing ag-grid in Angular 2

后端 未结 3 2355
無奈伤痛
無奈伤痛 2021-02-20 02:20

Has someone worked on unit testing ag-grid components in Angular 2?

For me, this.gridOptions.api remains undefined when the test cases run.

相关标签:
3条回答
  • 2021-02-20 03:03

    It remains undefined because the event onGridReady is not invoked yet. Im not sure about Angular 2 because im using angularjs and have to do $digest in order to invoke onGridReady.

    0 讨论(0)
  • 2021-02-20 03:11

    If you are using ag-grid enterprise make sure to include in your test file import 'ag-grid-enterprise'; otherwise you will see console errors and gridReady will never be called:

    Row Model "Server Side" not found. Please ensure the ag-Grid Enterprise Module @ag-grid-enterprise/server-side-row-model is registered.';
    
    0 讨论(0)
  • 2021-02-20 03:20

    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.

    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 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
    

    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
      }));
    
    0 讨论(0)
提交回复
热议问题