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

时间:2020-07-11 13:06:53

标签: angular unit-testing jasmine tdd

首先,我只是单元测试或一般测试的新手,所以我仍在围绕一些概念进行研究。已经掌握了单元测试的基础知识,并且我目前还正在学习rxjs大理石测试,因此目前我仍然坚持如何以与文档中的代码相同的方式来测试w / c函数的搜索。

因此,让我们在角度文档中使用来自英雄之旅的代码

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 个答案:

答案 0 :(得分:2)

我建议在单独的测试中测试链的每个部分(去抖动,差异,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);

}));


并为其他使用“正当原则”为链中其他运营商设置条件的测试编写类似的测试。