Mocking httpResource in Angular

httpResource is still experimental in Angular, and I've begun playing around with it. Once I got a working implementation on a simple form, I wanted to update my tests. This was challenging. I did some searching and found a couple of posts about using HttpTestingController and mocking a response, but I wanted to retain the service-level abstraction in my component unit tests, which know nothing about HTTP, only that services are used, and one of them now returns an HttpResourceRef in place of an Observable.

Here's the mock implementation I wrote. I'm using Vitest now in this project instead of Jasmine, but the syntax should hopefully still make sense.

class ExerciseServiceMock {
  get = vi.fn().mockImplementation(() => {

      const paginatedResults = new PaginatedResults<ExerciseDTO>();
      paginatedResults.totalCount = 0;
      paginatedResults.results = new Array<ExerciseDTO>();

      const mockResourceRef: Partial<HttpResourceRef<PaginatedResults<ExerciseDTO>>> = {
        value: signal(paginatedResults),
        isLoading: signal(false),
      };      

      return mockResourceRef
  });
}

By leveraging TypeScript's Partial<T>, I only needed to concern myself with the properties of the resource I care about. Once this was mocked, the test was easy to update.

Comments

Popular Posts

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

How to Determine if a Column Exists in a DataReader

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

Setting Default Values in an Angular Reactive Form