dimanche 31 janvier 2021

Angular and Jest: Mocking service is ignored

I have:

Service 1

@Injectable({ providedIn: 'root' })
export class OrganisationApiService {
  constructor(
     private httpClient: HttpClient,
     private env: EnvironmentService
  ) {}

  public getOrganisations(): Observable<Organisations[]> {
     return this.httpClient.get<Organisations[]>(this.env.environment.organisationApi);
  }
}

This service has EnvironmentService which just acts as a way to allow for injection of a a ts file which has an exported object, this object needs to be changed in certain circumstances (testing being one of them).

The test for this has the following setup block:

beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule]
    });
    TestBed.overrideProvider(EnvironmentService, { useValue: {} });
    organisationApiService = TestBed.inject(OrganisationApiService);
    httpMock = TestBed.inject(HttpTestingController);
});

Unfortunately what seems to be happening is instead of overriding the EnvironmentService it uses the original service, the original service has other dependencies and it obviously throws an error stating as much.

I originally used the providers section in the configureTestingModule definition but that did not work which is why I have tried to use the overrideProvider, at this point I am out of ideas.

Anyone got a solution?

Aucun commentaire:

Enregistrer un commentaire