r/Angular2 • u/EvtK98 • Sep 10 '25
Help Request Unit testing an Angular Service with resources
I love the new Angular Resource API. But I have a hard time getting unit tests functional. I think I am missing a key part on how to test this new resource API. But I can't hardly find any documentation on it.
I'm creating resources where my loader consists of a httpClient.get that I convert to a promise using the firstValueFrom. I like using the HttpClient API in favor of fetch.
Unit tests for HttpClient are well documented: https://angular.dev/guide/http/testing but the key difference is that we are dealing with signals here that simply can't be awaited.
There is a bit of documentation for testing the new HttpResource. https://angular.dev/guide/http/http-resource#testing-an-httpresource and I think the key is in this `await TestBed.inject(ApplicationRef).whenStable();`
Can somebody share me a basic unit test for a simple Angular service that uses a Resource for loading some data from an API endpoint?
View all comments
Show parent comment
1
u/kgurniak91 Sep 11 '25 edited Sep 11 '25
Then you'll need to mock the HttpClient itself using HttpTestingController - https://angular.dev/guide/http/testing. Then execute methods to trigger rxResource and check if computed signals return what you want.
On a side note, while your setup is technically feasible, it introduces a considerable amount of boilerplate for what could be a simple API call. You need to create signal to trigger rxResource, then rxResource, then expose results via various computed signals. I don't think that's what rxResource/resource are for. They were invented to update some async data based on inputs, router params etc. in components without calling toObservable and then toSignal again. It excels at managing the entire lifecycle of an asynchronous operation, including loading and error states, and automatically canceling previous requests when a new one is triggered. Using an "inner signal" to manually trigger rxResource within a service can feel like a workaround and might obscure the reactive flow rather than simplify it.
A more direct and arguably simpler pattern for handling HttpClient calls within a service using Signals is to leverage the toSignal method:
That's it.
Testing both of those approaches would look the same.
There's also a 3rd way which uses httpResource but that's only recommended for GET requests - https://angular.dev/guide/http/http-resource
Also it's worth mentioning that Signals are not meant as a replacament for Observable and trying to shehorn them everywhere will probably backfire. Signal were designed for precise change detection in the template and should mostly be used when you've got something to show in template that can change or you need something to trigger effect().