Reputation: 291
I'm writing a unit test to subscribe observable from a service. I'm getting pipe is not a function
error. I have created a jest spy for fundsListByClientId$
and simply returned the mock data. Please help me to know what I have missed? I'm using Jest for unit test
Error:
TypeError: this._fundsService.fundsListByClientId$.pipe is not a function
fund.spec.ts
let service: FundsService;
beforeEach(async () => {
await TestBed.configureTestingModule({
providers: [
{
provide: FundsService,
useValue: {
fundsListByClientId$: jest.fn(),
},
},
],
}).compileComponents();
});
beforeEach(() => {
service = TestBed.inject(FundsService);
});
it("Should sort fundlist object", () => {
const mockResponse = {cart: false, name: "test" };
const spyCopmponent = jest.spyOn(component, "onFundsByClientId");
jest
.spyOn(service, "fundsListByClientId$", "get")
.mockReturnValue(of(mockResponse));
component.onFundsByClientId();
service.fundsListByClientId$.subscribe((result) => {
expect(result).toEqual(mockResponse);
});
expect(spyCopmponent).toHaveBeenCalled();
});
fund.component.ts
onFundsByClientId() {
this._fundsService.fundsListByClientId$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((fundList: Fund[]) => {
this.fundList = fundList.sort((a, b) => {
if (a.fund_status === 'I' && b.fund_status !== 'I') return 1;
if (a.fund_status !== 'I' && b.fund_status === 'I') return -1;
return a.fund_name > b.fund_name ? 1 : -1;
});
this._changeDetectorRef.markForCheck();
});
}
fund.service.ts
private _fundList: BehaviorSubject<Fund[] | null> = new BehaviorSubject(null);
get fundsListByClientId$(): Observable<Fund[]> {
return this._fundList.asObservable();
}
getFundsListByClientId(clientId: string, filters?: any): Observable<Fund[]> {
const queryParams: HttpParams = UtilsService.buildQueryParams(filters);
return this.http
.get(this.endpoint, environment.fundApi + `/fund`, queryParams)
.pipe(
tap((response) => {
this._fundList.next(response);
}),
);
}
Upvotes: 5
Views: 5911
Reputation: 18809
Try changing the mock to this:
{
provide: FundsService,
useValue: {
fundsListByClientId$: of({cart: false, name: "test" }),
},
},
And get rid of this:
jest
.spyOn(service, "fundsListByClientId$", "get")
.mockReturnValue(of(mockResponse));
And see if it works.
I am not familiar with Jest but the way you mocked it with a jest.fn()
and using spyOn
on the get
might not work.
Upvotes: 5