mardi 30 mars 2021

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?

Aucun commentaire:

Enregistrer un commentaire