单元测试 - ag-grid API onFilterChanged 未定义 Angular 9

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

我正在 Angular 中为 Ag-grid 编写单元测试用例,其中我有 Angular Grid: External Filter,它正在切换过滤器复选框。 我收到 "TypeError: Cannot read 属性 'onFilterChanged' of undefined"

我正在测试这个方法:

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);
  });

我认为 gridApi 在您断言的那一刻未定义。测试 ag-grid 可能很奇怪,您必须等待其异步任务完成才能断言。

我会这样做:

像这样创建一个效用函数,您可以在其中等待某事为真,然后再继续:

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)
  });

是另一个和你有同样问题的人,如果你不喜欢我的,你可能想查看答案的解决方案。