gpt4 book ai didi

typescript - 预期对象是一种标量可观察对象,但它是可观察对象

转载 作者:行者123 更新时间:2023-12-04 17:47:59 27 4
gpt4 key购买 nike

在我的 Angular 应用程序中,我通过以下方式使用 Observables:

getItem(id): Observable<Object> {
return this.myApi.myMethod(...); // returns an Observable
}

我对它进行了单元测试:

it('getItem(...) should correctly do its job',
inject([MyService], (service: MyService) => {

const spy = spyOn(myApi, 'myMethod').and.returnValue(mockObservable);

const mockObservable = Observable.of('mock');

expect(service.getItem(123)).toEqual(mockObservable);

expect(spy).toHaveBeenCalledWith(...);
})
);

它工作得很好。

但是,如果我尝试添加 default error-handling logic使用 catch 到我的 getItem() 方法:

getItem(id): Observable<Object> {
return this.myApi.myMethod(...).catch(e => {
/* display a notification error ... */
return Observable.throw(e);
});
}

它仍然工作正常,但现在测试失败了,说:

Expected object to be a kind of ScalarObservable, but was Observable({ _isScalar: false, source: ScalarObservable({ _isScalar: true, value: 'mock', scheduler: null }), operator: CatchOperator({ selector: Function, caught: }) }).

这是什么意思?为什么会这样?我该如何解决这个问题?

最佳答案

感谢@Pace 的输入:

expect(service.getItem(123)).toEqual(mockObservable) fails because they are not the same object. The service method is returnning a new observable that wraps mockObservable and so the check fails. Your test would be better off subscribing to the observable returned from your service call and ensuring it returns 'mock'

我找到了解决方案:

it('getItem(...) should correctly do its job',
inject([MyService], (service: MyService) => {

const spy = spyOn(myApi, 'myMethod').and.returnValue(mockObservable);

const mockData = 'mock'; // can be anything
const mockObservable = Observable.of(mockData);


service.getItems().subscribe((data) => {
expect(data).toEqual(mockData);
});

expect(spy).toHaveBeenCalledWith(...);
})
);

关于typescript - 预期对象是一种标量可观察对象,但它是可观察对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47479099/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com