Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 unit testing a switchMap

Simple question:

I've followed the tutorial: here where I have the following code:

this.term.valueChanges
  .debounceTime(400)
  .distinctUntilChanged()
  .switchMap(term => this.wikipediaService.search(term));

Where term is a Control inheriting from AbstractControl, how can I trigger the valueChanges observable property, so that I can perform unit tests?

like image 363
Rhys Avatar asked Sep 15 '26 08:09

Rhys


1 Answers

I think I was experiencing the same issue. I was trying to test that heroService.searchHeroes was called:

  ngOnInit() {
    this.heroes$ = this.searchTerms
      .pipe(
        debounceTime(300),
        distinctUntilChanged(),
        switchMap((term: string) => this.heroService.searchHeroes(term))
      );
  }

I was able to fix it by only calling tick(500) once

  it('should call HeroService.searchHeroes', fakeAsync(() => {
    spyOn(heroService, 'searchHeroes').and.returnValue(component.heroes$);
    let searchField: DebugElement = fixture.debugElement.query(By.css('#search-box'));
    searchField.nativeElement.value = 'i';
    searchField.nativeElement.dispatchEvent(new Event('keyup'));
    tick(500);
    expect(heroService.searchHeroes).toHaveBeenCalled();
  }));
like image 66
Cameron Vogler Avatar answered Sep 17 '26 21:09

Cameron Vogler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!