Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function is never called inside a switchMap with unit test angular + jasmine and SpyOn

i'm trying do a test to know if a function of a service is called, but always it returns me that is not calling. I do not know what I'm doing wrong. The function that i want know if it's called this inside a switchMap, this function is a service. (this.heroSearchService.search(term))

This is the message that shows Expected spy search to have been called.

This is my component.

export class HeroSearchComponent implements OnInit {
  heroes: Observable<Hero[]>;
  private searchTerms = new Subject<string>();

  constructor(
    private heroSearchService: HeroSearchService
  ) {}

  search(term: string): void {
    // Push a search term into the observable stream.
    this.searchTerms.next(term);
  }

  ngOnInit(): void {    
    this.heroes = this.searchTerms.pipe(
      debounceTime(300), // wait for 300ms pause in events
      distinctUntilChanged(), // ignore if next search term is same as previous
      switchMap(term => term ? this.heroSearchService.search(term) : of<Hero[]>([])),
      catchError(error => {
        // TODO: real error handling
        console.log(`Error in component ... ${error}`);
        return of<Hero[]>([]);
      })
    );    
  }
}

This is my mock service.

export const MockHeroSearchService = {
    search: (term: string): Observable<Array<Hero>> => {
        let heroes = defaultHeroes.filter(hero => hero.name.includes(term)) as Array<Hero>;
        return of(heroes);
    }
}

This is my test file. Inside this file this the test where i created the spy (spyOn(heroSearchService, 'search').and.callThrough();) and the expect that fails is expect(heroSearchService.search).toHaveBeenCalled();

beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [CommonModule, HttpClientTestingModule, RouterTestingModule, FormsModule], //If our component uses routing, httpclient
            declarations: [HeroSearchComponent], //Here we put all the components that use our component. 
            providers: [
                //Here we can inject the dependencies that our component needs.
                //If our dependecies are services, we can create a simulated service.
                { provide: HeroSearchService, useValue: MockHeroSearchService },
            ]
        }).compileComponents();
    }));

    //Arrange
    beforeEach(() => {
        heroSearchService = TestBed.get(HeroSearchService);
        fixture = TestBed.createComponent(HeroSearchComponent);
        debugElement = fixture.debugElement;
        heroSearchComponent = fixture.componentInstance;
        //fixture.detectChanges();// Comments, so that it does run the of method ngOnInit();
    });

   fit('should with the correct search term, the variable heros have at least a hero', fakeAsync(() => {
        spyOn(heroSearchService, 'search').and.callThrough();
        fixture.detectChanges();

        const input = fixture.debugElement.query(By.css('#search-box'));
        input.nativeElement.value = 'And';
        input.triggerEventHandler('keyup', null);

        tick(600);
        fixture.detectChanges();

        expect(heroSearchService.search).toHaveBeenCalled();                       
    }));

I too run the code coverage and this is result. Where is shows that line is execute.

enter image description here

I hope you can help me. excuse me for my english.

like image 475
Andres Echeverry Avatar asked Nov 08 '22 02:11

Andres Echeverry


1 Answers

reviving this rather old threat as I have come across the same / similar issue. Have you beeen able to find a solution for it yet? In my case - thanks to logging intermediate values - I could verify that the ids$ Observable is firing.

this.testObs$ = this.ids$.pipe(
      switchMap(ids => {
        const promises = ids.map(id => {
          return this.testApi.getPayer(id).toPromise();
        });
        return Promise.all(promises);
      })
    );
like image 117
basti Avatar answered Nov 13 '22 20:11

basti