'How to test Angular component's observable error?

I want to test a component will render a ErrorComponent if one of the service or Gql fails, but I'm having trouble mocking the error where it triggers the catchError() block. Where do I mock that error? Inside the providers array? Using spyOn ? I tried both but not getting the results I want.

Component's ngOnInit() will set this.loading = isLoading and this.data$ = this.getData()

Inside getData()

combineLatest([
serviceA.get(),
serviceB.get(),
GqlC.fetch(),
GqlD.fetch(),
]).pipe(
      map(
        ([a,b,c,d]) => ({
            a,
         name: b[c],
         age : d
        })
      ),
      tap(() => {
        this.loading = isSuccess;
      }),
      catchError((e) => {
        this.loading = isFailure;
        return throwError(() => e);
      })
)

How do I mock an error returned from service or GQL to trigger the catchError block ?

Inside Spec

describe('aComponent error state', () => {
  let component;
  let fixture;
  let controller: ApolloTestingController;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [aComponent],
      providers: [
        { provide: serviceA,
          useValue: new mockServiceA({ mock }),},
        { provide: serviceB,
          useValue: new mockServiceB(mock), },
        { provide: APOLLO_TESTING_CACHE,
          useValue: new InMemoryCache({ addTypename: true }),},
      ],
      imports: [Module....],
    }).compileComponents();

    fixture = TestBed.createComponent(aComponent);
    component = fixture.componentInstance;
    controller = TestBed.inject(ApolloTestingController);
    fixture.detectChanges()
  });
  it('should render ERROR_COMPONENT', () => {

  });
});

I tried spyOn(component['GqlC'],'fetch').and.returnValue(throwError(()=>new Error('mockError'))) but I'm not getting any error component rendered at all.

Thank you for any inputs, I'm very new to angular and testing in general any help would be much appreciated.



Solution 1:[1]

Your mocks need to return appropriate Observables. For this particular test, have the service get methods and GqlC's fetch method return of(null) to make sure they emit, and have GqlD's fetch method return an Observable which errors out with throwError().

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Will Alexander