dimanche 26 janvier 2020

How can Angular's HttpClient services be tested properly?

I don't know if it's just in my code, but it seems to me that this is a general problem. Using the advocated method of testing HttpClient services, we don't really check that the value returned is correct.

This is the test that we're supposed to write for a service using HttpClient (https://angular.io/guide/http):

  const testData: Data = {name: 'Test Data'};

  // Make an HTTP GET request
  httpClient.get<Data>(testUrl)
    .subscribe(data =>
      // When observable resolves, result should match test data
      expect(data).toEqual(testData)
    );

  // The following `expectOne()` will match the request's URL.
  // If no requests or multiple requests matched that URL
  // `expectOne()` would throw.
  const req = httpTestingController.expectOne('/data');

  // Assert that the request is a GET.
  expect(req.request.method).toEqual('GET');

  // Respond with mock data, causing Observable to resolve.
  // Subscribe callback asserts that correct data was returned.
  req.flush(testData);

  // Finally, assert that there are no outstanding requests.
  httpTestingController.verify();
});

The problem seems to be that the test is already finished before the expect occurs. You can verify that by changing the service to still make the http request, but instead of returning its result, return a of(). The test still passes !

Am I missing something ? I've checked this numerous times so far, getting the same result each time.

Aucun commentaire:

Enregistrer un commentaire