Unit Test - ag-grid API onFilterChanged of undefined in Angular 9

Viewed 602

I am writing the unit test case for Ag-grid in Angular where I have Angular Grid: External Filter which is toggling filter checkbox. I'm getting "TypeError: Cannot read property 'onFilterChanged' of undefined"

I'm testing this method:

toggleCheckboxMethod({ checked }): void {
    isChecked = checked;
    this.gridApi.onFilterChanged(); //when this method initiates it causes for test to fail
  }
 beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule.withRoutes([]),
        HttpClientModule,
        HttpClientTestingModule,
        AgGridModule.withComponents([]),
        MatDialogModule,
        BrowserAnimationsModule
      ],
      declarations: [ TestComponent ],
      providers: []

    })
    .compileComponents();
  }));

beforeEach(() => {
    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
});

  it('should toggle checkbox', () => {
    let isChecked = false;
    spyOn(component, 'toggleCheckboxMethod').and.callThrough();
    component.toggleCheckboxMethod({ checked: true });
    expect(component.toggleCheckboxMethod).toHaveBeenCalled();
    expect(isChecked).toEqual(true);
  });
1 Answers

I think gridApi is undefined at that moment in time where you're asserting. Testing ag-grid can be strange where you have to wait for its asynchronous tasks to complete before asserting.

I would do something like this:

Create a utility function like so where you can wait for something to be true before carrying forward:

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);
};
it('should toggle checkbox', async (done: DoneFn) => {
    let isChecked = false;
    spyOn(component, 'toggleCheckboxMethod').and.callThrough();
    // wait until component.gridApi is truthy before carrying forward
    await waitUntil(() => !!component.gridApi);
    component.toggleCheckboxMethod({ checked: true });
    expect(component.toggleCheckboxMethod).toHaveBeenCalled();
    expect(isChecked).toEqual(true);
    done(); // call done to let Jasmine know you're done (this could be optional)
  });

This is another person having the same issue as you and you may want to check the answer's solution if you don't like mine.

Related