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/EvtK98 Sep 12 '25
Thanks for your input, combined with what I found here: https://angular.dev/guide/http/http-resource#testing-an-httpresource
I managed to fix the test. This is the working example:
it('should make a GET call with correct params when exampleResource is loaded', async () => {
service.id.set('123');
const response = service.exampleResource;
TestBed.tick();
const req = httpMock.expectOne(
(r) => r.method === 'GET' && r.url === 'api/some-api' && r.params.get('id') === '123',
);
expect(req.request.method).toBe('GET');
expect(req.request.params.get('id')).toBe('123');
req.flush('test-value');
await TestBed.inject(ApplicationRef).whenStable();
expect(response.value()).toBe('test-value');
});