我有一个组件,在 ngOninit 内部,我正在调度一个由 ngrx/effect 处理的操作,以从服务 API 获取一些数据。我正在编写单元测试并想在 ngOninit 中模拟服务调用,以便不调用原始 API。但是仍然调用了原始 API,可能是因为它是从效果中处理的。我应该如何处理这个问题,以便我停止实际的 API 调用并改为调用模拟服务 API?
组件代码:
ngOnInit() {
this.sectionId$ = this.store.select(reducers.getSectionIDFromAppState).subscribe((sectionID) => {
if (sectionID) {
this.store.dispatch(new layoutActions.GetLogFormatListAction(sectionID));
}
}
操作代码:
export class GetLogFormatListAction implements Action {
type = ActionTypes.GET_LOG_FORMAT_LIST;
constructor(public payload?: any) {
this.payload = payload;
}
}
效果代码:
@Effect()
getLogFormatList$: Observable<Action> = this.actions$
.ofType(layoutActions.ActionTypes.GET_LOG_FORMAT_LIST)
.mergeMap((action: any) => {
return this.layoutService.getLogFormatList(action.payload)
.map(logFormatList => new layoutActions.GetLogFormatListSuccessAction(logFormatList))
.catch(error => Observable.of(new layoutActions.GetLogFormatListFailureAction(error)));
});
布局服务.ts
getLogFormatList(sectionId): Observable<any> {
const requestData = {
endpoint: environment.endpoints.GET_LOG_FORMAT_LIST.endpoint + sectionId,
params: {
}
};
return this.httpRequestWrapperService.fetchData(requestData); }
我的规格代码:
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
LogviewerWidgetConfigComponent,
MockComponent({ selector: 'app-logviewer-config-template', inputs: ['logformatList', 'widgetConfig' , 'index'] }),
MockComponent({ selector: 'app-widget-config-header', inputs: ['model'], outputs: ['closeWidgetConfig'] }),
],
imports: [FormsModule, StoreModule.forRoot(reducers)],
providers: [{ provide: LayoutService, useClass: MockLayoutService }]
}).compileComponents(); }));
beforeEach(() => {
store = TestBed.get(Store);
spyOn(store, 'dispatch').and.callThrough();
fixture = TestBed.createComponent(LogviewerWidgetConfigComponent);
component = fixture.componentInstance;
fixture.detectChanges(); });
模拟服务:
class MockLayoutService {
getLogFormatList(param: any): Observable<any> {
return Observable.of(null);
}
}