Как выполнить модульное тестирование функции поиска? - PullRequest
0 голосов
/ 11 июля 2020

Во-первых, я новичок в модульном тестировании или тестировании в целом, так что я все еще пытаюсь понять некоторые концепции. У меня уже есть базовая c модульного тестирования, и я также в настоящее время изучаю rx js мраморное тестирование, поэтому в настоящее время я застрял на том, как тестировать поиск 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); */
    });
  });

Я просто могу не получается.

1 Ответ

2 голосов
/ 12 июля 2020

Я предлагаю протестировать каждую часть цепочки (debounce, disticnt, switchMap) в отдельном тесте.

Вы можете использовать Observer-Spy с комбинацией fakeAsync, чтобы было намного проще tests.

Например, чтобы протестировать 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);

}));


И напишите аналогичные тесты для других, которые используют «принцип ровно достаточно», чтобы настроить условия для других операторов в цепочке.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...