如何对搜索功能进行单元测试?

How to unit test search functionality?

首先,我只是单元测试或一般测试的新手,所以我仍在思考一些概念。已经掌握了单元测试的基础知识,我目前也在学习 rxjs 大理石测试,所以目前我还在研究如何测试搜索 w/c 功能,方法与文档中的代码相同。

所以让我们使用angular文档

中英雄之旅的代码
this.heroes$ = this.searchTerms.pipe(
  // wait 300ms after each keystroke before considering the term
  debounceTime(300),

  // ignore new term if same as previous term
  distinctUntilChanged(),

  // switch to new search observable each time the term changes
  switchMap((term: string) => this.heroService.searchHeroes(term)),
);

这是我当前的测试结果

const searchResults$ = (inputs$: Observable<string>) =>
  inputs$.pipe(
    debounceTime(300),
    distinctUntilChanged(),
    switchMap((term: string) => fakeHeroService.searchHeroes(term))
  );

  it('should return the correct results', () => {
    scheduler.run(helpers => {
      const { cold, hot, expectObservable } = helpers;

      // these are the search terms typed by user, observable
      // emitted by this.searchTerms
      const inputMarbles = '^-a 300ms b-c 300ms';

      // each emitted response by each service call
      const outputMarbles = '-- 300ms a-- 300ms c';

      // verify that service is called N times
      // verify that it's passed with certain argument per run


      searchServiceSpy = spyOn(heroService, 'searchHeroes').and.returnValue(
        cold(outputMarbles)
      );
      const source$ = hot(inputMarbles);

      const output$ = source$.pipe(searchResults$);

      expectObservable(output$).toBe(outputMarbles);

      /* expect(fakeSearchService.getMatches).toHaveBeenCalledTimes(2); */
    });
  });

我就是无法正常工作。

我建议在单独的测试中测试链的每个部分(去抖动、disticnt、switchMap)。

您可以使用 observer-spyfakeAsync 的组合来进行更简单的测试。

比如测试debounce可以这样写(以下代码可能不完整,只是为了说明问题)-

import {subscribeAndSpyOn} from '@hirez_io/observer-spy';

it('should debounce by 300 ms', fakeAsync(() => {

  // basically with "debounce" you only care if 2 triggers happened and enough time passed, 
  // the number of results should be 1...

  const observerSpy = subscribeAndSpyOn(serviceUnderTest.heroes$);
  serviceUnderTest.searchTerms.next();
  tick(100);
  serviceUnderTest.searchTerms.next();
  tick(300);
  expect(observerSpy.getValuesLength).toBe(1);

}));


并为其他人编写类似的测试,使用“刚好足够的原则”为链中的其他运营商设置条件。