[英]How can i test an observable that has pipe and map?
I'm assigning values to this variables inside ngOnInit:我在 ngOnInit 中为这个变量赋值:
this.simStatsList$ = this.sideMenuService.getSimStatsList();
this.currentStation$ = this.simStatsList$.pipe(
map(station => station.find((station: ISimStats) => station.stationName === this.authService.userStation)),
) as Observable<ISimStats>;
This is my test:这是我的测试:
it('should select userStation as currentStation', () => {
component.currentStation$.subscribe((response) => {
expect(response).toEqual(
{ stationName: 'test', stats: { open: 0, down: 0, preflight: 0 } }
);
});
});
It passes but is not covering the map function from rxjs. Also im providing sideMenuService and AuthService as mocked values and this is my mock.它通过但不涵盖 rxjs 中的 map function。我还提供 sideMenuService 和 AuthService 作为模拟值,这是我的模拟。 I'm missing something but i don't know what is it.
我错过了一些东西,但我不知道它是什么。
export const mockSideMenuService = {
getSimStatsList: () =>
of([
{ stationName: 'test', stats: { open: 0, down: 0, preflight: 0 } },
{ stationName: 'test1', stats: { open: 1, down: 1, preflight: 1 } }
] as ISimStats[])
}
export const mockAuthService = {
userStation: 'test'
}
Could you help me to cover the whole code?你能帮我覆盖整个代码吗?
After @will alexander comment i did some change and it worked:在@will alexander 发表评论后我做了一些改变并且它起作用了:
First, pass the function to the sideMenuService and recieve needed data as parameters:首先,将 function 传递给 sideMenuService 并接收所需数据作为参数:
side-menu.service.ts
getCurrentSimStats(
simStatsList$: Observable<ISimStats[]>,
currentStation: string): Observable<ISimStats> {
return simStatsList$.pipe(
map((station) => station.find((station: ISimStats) => station.stationName === currentStation))) as Observable<ISimStats>;
}
Then my component test coverage passed as 100% but the sideMenuService wasn't so i wrote this small test on service spec file:然后我的组件测试覆盖率通过了 100%,但是 sideMenuService 不是,所以我在服务规范文件上写了这个小测试:
side-menu.service.spec.ts
it('should getCurrentStation', () =>{
service.getCurrentSimStats(of(mockSideMenuService.mockSimStatsResponse), 'test').subscribe((res) => {
expect(res).toEqual(mockSideMenuService.mockCurrentSimStatsResponse);
});
})
After this, everything worked and tests are passing!在此之后,一切正常,测试通过!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.