mardi 12 novembre 2019

How do you write Angular tests for ag-Grid when using fakeAsync zone?

When testing ag-Grid in Angular applications using the fakeAsync zone, I receive the error Error: 4 timer(s) still in the queue.

I do not get this error if I just render my data to the screen without using ag-Grid and my tests pass.

Note that this is only an issue when testing with fakeAsync and if I test synchronously then tests with ag grid work as expected.

A full reproduction can be found on Github or Stackblitz. The project has an example with ag grid which fails and the same example without ag grid which passes.

In the example I have a search control on which I listen for value changes, debounce 300ms, and then fetch some data before populating the grid with the response data.

class WithAgGridComponent implements OnInit {
  constructor(private dataService: DataService) {}

  searchControl = new FormControl('');

  columnDefs = [
    { headerName: 'ID', field: 'id' },
    { headerName: 'Title', field: 'title' }
  ];

  rowData;

  modules = AllCommunityModules;

  ngOnInit() {
    this.searchControl.valueChanges
      .pipe(
        debounceTime(300),
        switchMap(value => this.dataService.fetch())
      )
      .subscribe(posts => (this.rowData = posts));
  }
}

My tests are as follows (using Spectator for readability). I mock the data request by waiting 100ms before returning the data.

describe('WithAgGridComponent', () => {
  let spectator: Spectator<WithAgGridComponent>;
  const createComponent = createComponentFactory({
    component: WithAgGridComponent,
    imports: [
      FormsModule,
      ReactiveFormsModule,
      AgGridModule.withComponents([])
    ],
    mocks: [DataService],
    detectChanges: false
  });

  it('should display the posts', fakeAsync(() => {
    spectator = createComponent();
    const dataService = spectator.get(DataService);
    dataService.fetch.andCallFake(() =>
      timer(100).pipe(mapTo([{ id: 1, title: 'testing ag grid' }]))
    );
    spectator.detectChanges();

    spectator.typeInElement('Test', 'input');

    tick(300);
    spectator.detectChanges();

    expect(spectator.query(byText('testing ag grid'))).not.toExist();

    tick(100);
    spectator.detectChanges();

    expect(dataService.fetch).toHaveBeenCalled();
    expect(spectator.query(byText('testing ag grid'))).toExist();
  }));
});

Aucun commentaire:

Enregistrer un commentaire