Angular Test Random Crash when I try to test interceptor

Viewed 229

I'm testing an Angular interceptor who test the refresh token before every api call

When the api response with an error the client must logout

Most of the time it works but some times i've got

Chrome 80.0.3987 (Windows 10.0.0) ERROR An error was thrown in afterAll HttpErrorResponse: Http failure response for https://localhost:44310/api/autoauth/refreshtoken: 401 Unauthorized

and after

Chrome 80.0.3987 (Windows 10.0.0) ERROR Disconnected, because no message in 30000 ms.

Here

class SubjectAuthService extends AuthenticationService {
  logout() { }
}

describe(`JwtRefreshInterceptor`, () => {
  let service: FamilyService;
  let httpMock: HttpTestingController;
  let authenticationService: AuthenticationService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
        RouterTestingModule,
        GtagTestingModule,
      ],
      providers: [
        FamilyService,
        { provide: AuthenticationService, useClass: SubjectAuthService },
        { provide: 'familyTableName', useValue: 'families' },
        {
          provide: HTTP_INTERCEPTORS,
          useClass: JwtRefreshInterceptor,
          multi: true,
        },
      ],
    });


    authenticationService = TestBed.get(AuthenticationService);
    service = TestBed.get(FamilyService);
    httpMock = TestBed.get(HttpTestingController);

  });


  it('should logOut because no current user', () => {
    spyOn(authenticationService, 'logout');

    service.fetchFamilies().subscribe();
    httpMock.expectNone(`${environment.api}/family?catalogId=0`);

    const refreshRequest = httpMock.expectOne(`${environment.api}/autoauth/refreshtoken`);
    expect(refreshRequest.request.method).toBe('POST');

    refreshRequest.flush(null, {
      status: 401,
      statusText: 'Unauthorized',
    });

    expect(authenticationService.logout).toHaveBeenCalled();
  });
1 Answers

you need to catch the error in the subscribe

.subscribe(() => {}, error =>  {})
Related