I have a component method with this format:
action(): Observable<void> {
return this.service.actiontaken(this.ids).pipe(
switchMap(() => {
return this.otherMethod(this.ids);
}),
);
}
I am able to test the part upto this.service.actiontaken
, but the test I wrote is not reaching the area within switchMap.
it('action(): should call the service method', () => {
service.actiontaken.mockReturnValue(of());
const otherActionSpy = jest.spyOn(component, 'otherAction').mockReturnValue(of());
fixture.detectChanges();
component.action();
expect(service.actiontaken).toHaveBeenCalledTimes(1);
expect(otherActionSpy).toHaveBeenCalledTimes(1); // this part fails, and in coverage the part under switchMap is also not covered
});
Please help on how to proceed with this.
Found the solution to this:
Since action
returns an Observable, subscribing to it will reach within switchMap.
it('action(): should call the service method', () => {
service.actiontaken.mockReturnValue(of());
const otherActionSpy = jest.spyOn(component, 'otherAction').mockReturnValue(of());
fixture.detectChanges();
component.action().subscribe(() => {
expect(otherActionSpy).toHaveBeenCalledTimes(1);
});
expect(service.actiontaken).toHaveBeenCalledTimes(1);
});