Joh*_*nny 5 unit-testing observable rxjs jestjs angular
我正在编写一个单元测试来从服务订阅可观察的内容。我收到pipe is not a function错误。我创建了一个玩笑间谍fundsListByClientId$并简单地返回了模拟数据。请帮助我知道我错过了什么?我使用 Jest 进行单元测试
错误:
TypeError: this._fundsService.fundsListByClientId$.pipe is not a function
Run Code Online (Sandbox Code Playgroud)
基金规格
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();
});
Run Code Online (Sandbox Code Playgroud)
基金组件.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();
});
}
Run Code Online (Sandbox Code Playgroud)
基金服务.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);
}),
);
}
Run Code Online (Sandbox Code Playgroud)
尝试将模拟更改为:
{
provide: FundsService,
useValue: {
fundsListByClientId$: of({cart: false, name: "test" }),
},
},
Run Code Online (Sandbox Code Playgroud)
并摆脱这个:
jest
.spyOn(service, "fundsListByClientId$", "get")
.mockReturnValue(of(mockResponse));
Run Code Online (Sandbox Code Playgroud)
看看它是否有效。
我不熟悉 Jest,但你用 a 嘲笑它jest.fn()并使用spyOnon the 的方式get可能行不通。
| 归档时间: |
|
| 查看次数: |
4580 次 |
| 最近记录: |