#How to test http services that have a Resource property, that loads itself?

4 messages · Page 1 of 1 (latest)

tender path
#

I'm having this snippet of code in a service

  readonly timezones = resource({
    loader: () => {
      return firstValueFrom(this.getAll()).catch(() => {
        return [];
      });
    }
  });
  readonly #apiService = inject(ApiService);
  public getAll(): Observable<TimezoneWithFacilitiesResponse[]> {
    return this.#apiService.get<TimezoneWithFacilitiesResponse[]>(`${this.apiUrl}/GetAll`);
  }

When i try to use the HttpTestingController I always end up with an error in the test

let httpMock: HttpTestingController;
  let service: TimezonesService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        makeEnvironmentProviders([
          {
            provide: AppSettings,
            useValue: settingsMock
          }
        ]),
        provideHttpClient(),
        provideHttpClientTesting(),
        ApiService,
        TimezonesService
      ]
    });

    httpMock = TestBed.inject(HttpTestingController);
    service = TestBed.inject(TimezonesService);
  });

  afterEach(() => {
    httpMock.verify();
  });
 it('should get all time zones', waitForAsync(() => {
    const expectedResponse = timezonesMock as TimezoneWithFacilitiesResponse[];
    // service.timezones.value();
    service.getAll().subscribe((response) => {
      expect(response).toEqual(expectedResponse);
    });

    const testUrl = `${settingsMock.url}/${service.apiUrl}/GetAll`;

    const request = httpMock.expectOne({
      method: HttpMethod.GET,
      url: testUrl
    });

    request.flush(expectedResponse);
  }));
});

I end up with one open request. How to deal with this?

clear eagle
#

Well, you are triggering getAll twice. once by calling getAll from the resource, once by calling from the test directly.

tender path
#

Yes, it seems that way, but how to deal with this , I'm not sure about the way to expect multiple calls with the controller.
The only thing i have found is to set the value of the resource to something different then undefined, then the loader doesn't trigger. But this is sorta ....meh

clear eagle
#

Why not test the resource instead of getAll?