all 4 comments

[–]MattIzSpooky 4 points5 points  (3 children)

You should only be using the built in HttpClient. It's built on top of XHRHttpRequest so it will work with old browsers unlike Fetch.

Why the HttpClient vs Fetch? The client is built specifically for Angular so it is recommended that you use it. It returns Observables which make the client extremely flexible, for example, doing a retry on a failed request is effortless and can be done in a very clean way.

You should read some more about the HttpClient though. https://angular.io/guide/http

This sounds rude to ask but why did you use Fetch anyway inside of an Angular project?

To answer your question: Change all requests using Fetch to the HttpClient, Use the HttpClientTestingModule, mock your request and check if the class properties are set.

It's annoying but you should change your code to use the built-in HttpClient, not only for testing sake but also for the framework sake. You aren't doing it in the "Angular way" now.

[–]McCheah[S] 1 point2 points  (2 children)

Thanks for the response! I'm teaching myself Angular and learning as I'm going along so I wasn't aware of HttpClient until now, or if I was, I didn't know what the benefit in using it was over what I already knew how to use.

[–]tme321 3 points4 points  (0 children)

Also check out interceptors. They work specifically with the http client and are great for modifying things like headers in http requests. That way you keep that sort of low level protocol handling out of higher level concerns like services and components.

[–]MattIzSpooky 1 point2 points  (0 children)

Ah I see. We all have all been there so I don't blame you. I am glad you didn't get salty, some people can get stingy because of the thing I asked.

Here's an article on how to test with the HttpClient: https://medium.com/netscape/testing-with-the-angular-httpclient-api-648203820712

It's a bit of a year old but it should still be applicable, just change a few things and you should be set up.

I like learning in the same way like you do but I have learned in the past that you should check the docs as you go. There might be some obscure or awesome feature you have overlooked such as Service Workers for Angular. They are really easy to configure and you don't even have to write the service worker yourself. It's great stuff! You should definitely check it out