在带有单元测试angular + jasmine和SpyOn的switchMap内部永远不会调用函数

时间:2018-09-19 19:12:33

标签: angular unit-testing jasmine rxjs spyon

我正在尝试进行测试,以了解是否调用了服务的功能,但始终会返回未调用的服务。我不知道我在做什么错。 我想知道的功能是否在switchMap中被称为此功能,该功能是一项服务。 (this.heroSearchService.search(term))

这是显示Expected spy search to have been called.

的消息

这是我的组件。

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

这是我的模拟服务。

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

这是我的测试文件。在此文件中,此测试是我在其中创建间谍(spyOn(heroSearchService, 'search').and.callThrough();)的测试,并且失败的期望是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();                       
    }));

我也运行了代码覆盖率,这就是结果。在哪里显示该行正在执行。

enter image description here

希望您能帮助我。请原谅我的英语。

1 个答案:

答案 0 :(得分:0)

重温这个相当古老的威胁,因为我遇到了相同/相似的问题。您有能力找到解决方案吗? 就我而言-由于记录了中间值-我可以验证ids $ Observable是否正在触发。

this.testObs$ = this.ids$.pipe(
      switchMap(ids => {
        const promises = ids.map(id => {
          return this.testApi.getPayer(id).toPromise();
        });
        return Promise.all(promises);
      })
    );