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

标签 typescript jasmine rxjs angular-observable angular-test

在我的 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/

相关文章:

javascript - 使用 requireJs 在 Jasmine 中模拟匿名模块调用

javascript - JasmineJS 'isNot' 属性

javascript - 如何使用 RxJS 控制多个 ajax 调用的压力

javascript - 如何将 RxJs 连接到 React 组件

Angular 2无法使模型对象的json常量

Typescript + Vue + Element-ui

reactjs - 使用 react-redux connect 函数时渲染组件出现 Typescript 错误

javascript - 从提供者函数获取值到另一个页面

AngularJS promise 在使用 Jasmine 进行测试时不会调用 then

rxjs - RXJS:总计反跳