How can I mock an Observable.throw in an Angular2 test?

泪湿孤枕 提交于 2019-12-22 01:55:17

问题


I want to test the error handling in my Angular2 component and therefore want to mock a service to return an Observable.throw('error'). How can that be done using Jasmine and Karma and Angular 2?


回答1:


You should create an observable, and just call the observer error. For example

let mockService = {
  error: false,
  data: 'something',
  getData: () => {
    return Observable.create(observer => {
      if (this.error) {
        observer.error(new Error(..))
      } else {
        observer.next(this.data);
      }
      observer.complete();
    })
  }
}

Now for your tests, you can use the mock for both success cases and error cases. For an error case, just set the error property to true. In the success case, next is called with the data.

When you subscribe to an observable, you can pass three callback, success, error, and complete

service.getData().subscribe(
  (data) => {}   // sucess
  (error) => {}  // error
  () => {}       // complete
)

So with the observer, when calling observer.next, observer.error, observer.complete, the corresponding callback will be called.




回答2:


Here is my solution for the ones using Rxjs 6

let mockService = {
  getData: () => {
    return of({data:'any data'});
  }
}

spyOn(mockService , 'getData').and.callFake(() => {
  return throwError(new Error('Fake error'));
});



回答3:


You can simply mock Observable and throw error object using Observable.throw({status: 404}) and test error block of observable.

const xService = fixture.debugElement.injector.get(SomeService);
const mockCall = spyOn(xService, 'xMethod')
                       .and.returnValue(Observable.throw({status: 404}));

Here I am throwing http 404 error from Observable.throw({status: 404}) by mocking xMethod of xSerive in my test.



来源:https://stackoverflow.com/questions/40969759/how-can-i-mock-an-observable-throw-in-an-angular2-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!