I'm having a service that looks more less like this
getData(properties: any): Observable<any[]> {
const qrList$: Observable<any[]> =
properties.type === 'e'
? this.getByE(properties)
: this.getByD(properties);
return qrList$.pipe(
map((qrList) => this.filter(qrList));
}
private getByE(properties: any): Observable<any[]> {
let request$: Observable<any[]>;
if (properties.o === 'c') {
request$ = this.qrService.getQ();
} else {
request$ = this.eService.getEncByE()
.pipe(
map((encList: any[]) => this.getFinished(encList)),
switchMap((list) => {
return previousEncounterIdList?.length > 0
? this.qrService.getQ()
: of([]);
}),
);
}
return request$;
}
and my spec file
...
beforeEach(() => {
spyOn(eService, 'getEncByE').and.returnValue(of([{}]));
spyOn(qrService, 'getQ').and.returnValue(of([]));
});
...
it('whatever', fakeAsync(() => {
propertiesMock.type = 'e';
propertiesMock.o = 'p';
service.getData(propertiesMock);
tick();
expect(eService.getEncByE).toHaveBeenCalled();
expect(qrService.getQ).toHaveBeenCalled();
}));
the last line of code expect(qrService.getQ).toHaveBeenCalled();
throws an error that the spy was never called, how can I reach this part of code?
CodePudding user response:
Since service.getData()
returns an Observable
, you have to subscribe
to it for the subscription to "take flight".
Try this:
it('whatever', fakeAsync(() => {
propertiesMock.type = 'e';
propertiesMock.o = 'p';
// mock getEncByE
spyOn(eService, 'getEncByE').and.returnValue(of([]));
// have to maybe do some more mocking as well
service.getData(propertiesMock).subscribe(() => {
expect(eService.getEncByE).toHaveBeenCalled();
expect(qrService.getQ).toHaveBeenCalled();
});
tick();
}));