我在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>;
这是我的测试:
it('should select userStation as currentStation', () => {
component.currentStation$.subscribe((response) => {
expect(response).toEqual(
{ stationName: 'test', stats: { open: 0, down: 0, preflight: 0 } }
);
});
});
它通过了,但没有覆盖rxjs中的map函数。我也提供了sideMenuService和AuthService作为模拟值,这是我的模拟。我错过了一些东西,但我不知道是什么。
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'
}
你能帮我覆盖整个代码吗?
在@will alexander评论之后,我做了一些改变,它起作用了:
首先,将函数传递给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>;
}
然后我的组件测试覆盖率通过了100%,但sideMenuService不是,所以我在服务规范文件上写了这个小测试:
side-menu.service.spec.ts
it('should getCurrentStation', () =>{
service.getCurrentSimStats(of(mockSideMenuService.mockSimStatsResponse), 'test').subscribe((res) => {
expect(res).toEqual(mockSideMenuService.mockCurrentSimStatsResponse);
});
})
在此之后,一切正常,测试通过了!