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



首先,我只是单元测试或一般测试的新手,所以我仍然在思考一些概念。我已经掌握了单元测试的基本知识,目前也在学习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); */
});
});

我就是不能让它工作。

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

您可以将observer spy与fakeAsync组合使用,以便进行更简单的测试。

例如,为了测试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);
}));

并为使用";"适可而止"原则;为链中的其他操作员设置条件。

最新更新