Testing error case with observables in services

后端 未结 2 704
离开以前
离开以前 2020-11-30 03:34

Let\'s say I have a component that subscribes to a service function:

export class Component {

   ...

    ngOnInit() {
        this.service.doStuff().su         


        
2条回答
  •  鱼传尺愫
    2020-11-30 04:14

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

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

    Update 2019 :

    Since some people are lazy to read comment let me put this here : It's a best practice to use errors for Rxjs

    import { throwError } from 'rxjs'; // make sure to import the throwError from rxjs
    const xService = fixture.debugElement.injector.get(SomeService);
    const mockCall = spyOn(xService,'method').and.returnValue(throwError({status: 404}));
    

提交回复
热议问题