AG 调用 gridApi 函数的网格单元测试(即:gridApi.setQuickFilter)

问题描述 投票:0回答:1

我有一个调用“gridApi.setQuickFilter”的函数,我需要测试它是否使用正确的参数进行调用。

组件:

  clearQuickFilter = () => {
    this.quickFilter = '';
    this.gridApi.setQuickFilter('');
  };

我对此进行单元测试的尝试给了我一个错误

Error: <spyOn> : could not find an object to spy upon for setQuickFilter()
,不幸的是我无法解决这个问题。

规格:

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [MyComponent],
      imports: [AgGridModule],
      providers: [...],
      schemas: [NO_ERRORS_SCHEMA],
    });

    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;

    fixture.detectChanges();
  });

  describe('quick filters', () => {
    it('should clear quickfilters', () => {
      const quickFilterSpy = spyOn(
        component.gridApi,
        'setQuickFilter'
      );  // the test fails on this line with the error above

      component.clearQuickFilter();

      expect(component.quickFilter).toBe('');
      expect(quickFilterSpy).toHaveBeenCalledWith('');
    });
  });
});

如何模拟 gridApi 函数,如

setQuickFilter
等?

angular jasmine ag-grid
1个回答
0
投票

创建一个模拟对象,然后错误就会消失。在测试过程中,gridApi 不会有值,我们还需要模拟该对象!

以下更改将消除您的错误!

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [MyComponent],
      imports: [AgGridModule],
      providers: [...],
      schemas: [NO_ERRORS_SCHEMA],
    });

    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;

    fixture.detectChanges();
  });

  describe('quick filters', () => {
    it('should clear quickfilters', () => {
      component.gridApi = { // <-- changed here
          setQuickFilter: () => {}, // <-- changed here
      } as any; // <-- changed here
      const quickFilterSpy = spyOn(
        component.gridApi,
        'setQuickFilter'
      );

      component.clearQuickFilter();

      expect(component.quickFilter).toBe('');
      expect(quickFilterSpy).toHaveBeenCalledWith('');
    });
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.