mercredi 8 juillet 2020

Angular HttpTestingController doesn't find matches

My aim is to test an http response interceptor. Therefore I use the HttpClient to make a fake request and the HttpTestingController to provide a fake error response.

I've followed this Angular tutorial. Unfortunately I'm getting the error:

Expected one matching request for criteria "Match URL..."

It's strange because I'm using the same testUrl both for expectation and call. Here is my code (for now, I only want to verify, that the request actually "arrives" at the testing controller):

  let httpClient: HttpClient;
  let httpMock: HttpTestingController;
  const testUrl = "/abc";

  beforeEach(() => {
    TestBed.configureTestingModule(
      {
        providers: [
          {
            provide: HTTP_INTERCEPTORS,
            useClass: HttpUnauthorizedInterceptor,
            multi: true
          }
        ],
        imports: [HttpClientTestingModule]
      });

    httpClient = TestBed.inject(HttpClient);
    httpMock = TestBed.inject(HttpTestingController);

  });

  it('should navigate to login page on 401 response code', () => {

    httpClient.get<any>(testUrl).subscribe(
      () => { },
      () => { }
    );

    const httpRequest = httpMock.expectOne(testUrl);
    expect(httpRequest.request.method).toEqual('GET');

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

  });

Maybe you will have any ideas how to fix this...

Aucun commentaire:

Enregistrer un commentaire