Writing test to make sure function is called from subscribe block

  angular, jasmine, rxjs, unit-testing

I am trying to write a test for the following subscribe block inside MyComponent

ngOnInit() {
// Initalize listener for year dropdown change
    this.yearChangeSubscription = this.searchForm.get('year')?.valueChanges.pipe(
      debounceTime(400),
      distinctUntilChanged(),
      switchMap((year: string) => {
        return of(year);
      })
    ).subscribe((year: string) => {
      console.log('yearChange');
      this.filterData({ year });
    });
}

I want to ensure the filterData function gets called when I change the value in year form control. So I wrote the following spec.

fit('should call filterData', fakeAsync(() => {
    component.searchForm.controls.year.setValue('2005');
    fixture.detectChanges();
    flush();
    const spy: any = jasmine.createSpyObj('MyComponent', ['filterData']);
    expect(component.searchForm.controls.year.value).toEqual('2005');
    expect(spy.filterData).toHaveBeenCalledTimes(1);
  }));

the first expectation is passing but the second is failing.
I can see the yearChange console log on the terminal.

Any Idea what I am doing wrong here?

Source: Angular Questions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.