1

In my Angular application, I'm using Observables in the following way:

getItem(id): Observable<Object> {
  return this.myApi.myMethod(...).catch(e => {
    /* CATCH BODY */
    return Observable.throw(e);
  });
}

and I unit test it:

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(...);
  })
);

However, I don't know how to unit test the CATCH BODY, how can I mock the observable to throw an error?

I know similar questions have been asked already, but my case is slightly different and I couldn't succeed in unit testing the catch part.

4

1 回答 1

2

创建另一个it块,而不是使用Observable.ofuse Observable.throw,它将创建一个Observable不发出任何项目并以错误终止的块

it('getItem(...) should fail',
  inject([MyService], (service: MyService) => {
    const mockData = 'mock'; // can be anything
    const mockObservable = Observable.throw(mockData); // make it fail

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

    service.getItems().subscribe(
        (data) => { 
            // success
        },
        (error) => { 
            expect(error).toEqual(mockData);
        }
    );

    expect(spy).toHaveBeenCalled();
  })
);

希望能帮助到你

于 2017-11-27T20:19:22.373 回答