2

我有一个组件,在 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);
  }
}
4

1 回答 1

0

你没有模拟你的 API 调用,你模拟了另一个服务。

如果你想模拟你的 API 调用,做这个模拟:

const storeMock = {
  select: () => Observable.of(null),
  dispatch: () => null
};

并在您的测试台上提供它:

providers: [
  { provide: LayoutService, useClass: MockLayoutService },
  { provide: Store, useValue: storeMock }
]

(我不知道您正在使用的依赖项,但我认为imports如果您模拟它的服务,您可能必须从您的 StoreModule 中删除)。

完成后,您的调用将不再命中 API,而是命中模拟。

于 2018-06-14T07:27:39.053 回答