I'm in the process of writing unit tests for my Angular application. I need to mock the data returned by a service for HTTP calls.
component.spec.ts
let apiService: ApiService;
let mockedHttpClient: HttpClient = mock(HttpClient);
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [EditorComponent],
providers: [
{ provide: ApiService, useValue: apiService },
{
provide: HttpClient,
useFactory: () => instance(mockedHttpClient),
},
],
imports: [HttpClientModule],
}).compileComponents();
});
beforeEach(() => {
apiService = TestBed.inject(ApiService);
fixture = TestBed.createComponent(EditorComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it("should retrieve information", (done: DoneFn) => {
component.id = "id1";
spyOn(apiService, "getInfosById").and.returnValue(of(infos));
component.getInformations();
expect(component.infos).toEqual(infos);
});
component.ts
private readonly unsubscribe = new Subject();
getInformations() {
this.apiService
.getInfos(this.id)
.pipe(takeUntil(this.unsubscribe))
.subscribe((data) => {
this.infos = data;
})
}
ngOnDestroy() {
this.unsubscribe.next();
this.unsubscribe.complete();
}
api-service.ts
public getInfos(id: string) {
return this.http.get<Infos>(
this.apiUrl +'infos/' + id,
httpOptions)}
I'm looking to mock the function mentioned above.
Error
<spyOn> : could not find an object to spy upon for getInformations()
What could be the issue here? Are there better ways to mock an HTTP service with .pipe and .subscribe?