如何在茉莉花中测试RxJs回调

时间:2018-02-22 14:27:28

标签: angular jasmine rxjs ng-bootstrap

我在我的组件中使用NgbTypeAhead,其中回调必须是 (text: Observable<string>) => Observable<any[]> 。现在,我想测试搜索的副作用,但我很难在茉莉花中编写该测试。

有人可以帮忙吗?提前致谢。

component.ts

search = (text$: Observable<string>) =>
        text$
            .debounceTime(200)
            .distinctUntilChanged()
            .do((term: string) => {
                console.log("do 1", term)
                this.isSearching = true && term !== "";
                this.cd.markForCheck();
            })
            .map(term => {
                console.log("map", term)
                return term === ""
                    ? this.list
                    : this.filter(term)
            })
            .do(list => {
                console.log("do 2", list)
                this.searchResultsCount = list.length;
                this.cd.markForCheck();
            });

component.html

<input #initiativeSearch type="text" id="initiativeSearch" 
    [ngbTypeahead]="search"/>

component.spec.ts

 it("should update searching flags", () => {
       // how do I test this ? here is what I tried
        let spyObj = jasmine.createSpyObj<Observable<string>>("text$", ["debounceTime", "distinctUntilChanged", "do", "map"]);

        spyObj.debounceTime.and.returnValue(spyObj)
        spyObj.distinctUntilChanged.and.returnValue(spyObj)
        spyObj.do.and.returnValues(Observable.of("blabla"), Observable.of([]))
        spyObj.map.and.returnValue(Observable.of([]))
        component.searchInitiatives(spyObj);

        expect(spyObj.debounceTime).toHaveBeenCalledWith(200);
        expect(spyObj.distinctUntilChanged).toHaveBeenCalledTimes(1);
        expect(spyObj.do).toHaveBeenCalledTimes(2);
    });

这会在控制台中记录spy text$.do to have been called 2 times. It was called 1 times.,但不会显示任何console.log

2 个答案:

答案 0 :(得分:1)

听起来你正在以错误的方向进行测试。如果您是单元测试,您需要做的就是一次测试一个组件。

您只需要直接测试搜索组件。你可以这样做:

let observableSpy = {
  debounceTime: observableSpy,
  distinctUntilChanged: observableSpy,
  // ... repeat for all properties
};
let spyObj = jasmine.createSpyObj(observableSpy);

然后将spyObj传递给您的搜索功能:

search(spyObj)

最后,运行一些断言:

expect(spyObj.debounceTime).toHaveBeenCalledWith(...);
// ... test all calls.

这样做更像是单元测试。

答案 1 :(得分:0)

您可以测试此功能,但您需要在Angular&#34;家庭区域&#34;之外测试它。与fakeAsync装饰器。

那说我强烈建议不要这样做。对我而言,您似乎正在尝试测试不在单元测试范围内的ReactiveX运算符。使用这些库时,应该假设库具有自己的单元测试。您可能希望测试传递的正确值(以毫秒为单位),但您实际上并不需要或想要测试debounceTime运算符。

请告诉我们这是否有意义,如果没有,我们可以找到其他更好的方法来找到您的断言的覆盖范围,但测试RXJS框架实际上不是我建议集中精力的东西。

相关问题