Search code examples
testingkarma-jasmineangular8karma-coverage

Angular 8 karma test both success and error of Observable from service


I'm testing MyComponent that, in ngOnInit, calls a service method that returns an observable:

    this.myService.getMyData().subscribe(
        (data) => {
            //do something
        },
        (error) => {
            //do something - error
        }
    );

I've installed a spy on getMyData, this way:

mySpy = spyOn(myService, 'getMyData').and.returnValue(of(mockObject));

and this covers the "success branch" of subscribe. But I need also to cover the "error branch". I've tried doing this:

spyOn(myService, 'getMyData').and.returnValue(throwError(new Error('Error')));

but of course Jasmine tells me that getMyData has already been spied upon. How can I cover both branches?


Solution

  • What you are doing is correct but, you can't spy on the same service more than once in the same test case.

    Hence you need to write a second test case which will cover your error scenario.

    Something like this:

    it('should run success scenario', () => {
       mySpy = spyOn(myService, 'getMyData').and.returnValue(of(mockObject));
    })
    
    it('should run error scenario', () => {
       mySpy = spyOn(myService, 'getMyData').and.returnValue(throwError(new Error('Error')));
    })