Search code examples
angularjasmineag-grid

AG Grid unit testing that gridApi functions are called (ie: gridApi.setQuickFilter)


I have a function that calls `gridApi.setQuickFilter', and I need to test that it is getting called with the correct arguments.

component:

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

My attempt at a unit test for this gives me an error Error: <spyOn> : could not find an object to spy upon for setQuickFilter() and unfortunately I haven't been able to resolve this.

spec.ts:

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

How can I mock gridApi functions like setQuickFilter and others?


Solution

  • Create a mock object, then the error will go away. During testing gridApi will not have values, we need to mock the object also!

    the below change will get rid of your error!

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