How to properly test the return of a resolver service in Angular

Viewed 608

I am finding testing in Angular very difficult. In an attempt to deal with as little boilerplate as possible, I have attempted to go for jest/spectator unit tests.

I would like to test a resolver. Either it should return an Observable of type Contact[] or EMPTY from catchError(). There are only two outcomes.

The following is what I have so far and I know it is rough.

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | 
   Observable<never> {
  return this.contactsService.getContacts()
    .pipe(
      catchError(err => EMPTY),
      tap(res => res)
    );

}

describe('ContactsResolverService', () => {
 let spectator: SpectatorService<ContactsResolverService>;

 const createService = createServiceFactory({
   service: ContactsResolverService,
   imports: [HttpClientModule]
 });

 beforeEach(() => {
   spectator = createService();
  });

 it('should call the resolve class method', fakeAsync ( () => {

   const contactsService = spectator.inject(ContactsService);
   contactsService.getContacts.andReturn( of( ['ContactObj', 'ContactObj', 'ContactObj']) );
   const mockSnapshot = createSpyObj<RouterStateSnapshot>('RouterStateSnapshot', 
   ['toString']);
   const mockR = createSpyObj<ActivatedRouteSnapshot>('ActivatedRouteSnapshot', 
   ['toString']);
   flushMicrotasks();
   const r = spectator.service.resolve(mockR, mockSnapshot)
   expect(r).toHaveBeenCalled();
  }));

});
0 Answers
Related