Discussion on: Intercepting Http Requests-- Using And Testing Angular's HttpClient

yannbertrand profile image
Yann Bertrand

Thanks, Alisa, for that article.

I really don't like the way we have to do that in Angular. For those who didn't try it out, let me explain what happen in terms of timeline:

  • .subscribe() launch a request and give a callback to be called once we get the response.
  • .expectOne() verify that an endpoint has been called
  • .flush() respond to that request
  • the subscribe callback gets called, and we can finally verify that we have a correct answer.

By the way, the order of the code is really important, if you move just one line of it, the test breaks.

In my sense, we should be able to write it like:

  • describe that when a request to /whatever is sent, we pass a mock answer (or throw if that's what we want to test)
  • launch the request
  • verify the answer

That would be way easier to explain to people and let us put our mocked request => response in a beforeEach!

How do you feel about it?

alisaduncan profile image
Alisa Author

Hi there! Sorry it took me so long to respond; I didn't see this comment until now. 😬

I hear what you're saying, it is a lot of steps and I've made the mistake of not calling .flush() when testing myself. However, I do like that Angular's HttpClientTestingModule allows me to verify expected number of times a call is made without using a Jasmine spy. I also like that I can verify the HTTP method used in the call, headers, etc separately from verifying the subscribe portion.

For more complicated service calls (where there's retries, different HTTP methods, or custom headers), being able to assert separately starts making more sense.

For straightforward requests like what I have in this post, having an all-in-one solution like what you propose is a great way to go and definitely helps to make things easier. 🙂

Thank you for taking the time to read and comment! These kinds of discussions are great!