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

后端 未结 3 969
不思量自难忘°
不思量自难忘° 2021-02-18 21:54

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

3条回答
  •  情书的邮戳
    2021-02-18 22:24

    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.

提交回复
热议问题