我创建了此函数,因为对于我的应用程序使用http.post
发送的所有请求,这是不同部分处理响应的方式。因此,我认为不是创建代码,而是创建一个函数。但是我无法弄清楚如何对该功能进行单元测试。
private editAnswerSubject: Subject<Result>;
subscribeToReturnedObservable(observable:Observable<any>, subject:Subject<Result>) {
observable.subscribe((res) => {
const ev = <HttpEvent<any>>(res);
if (ev.type === HttpEventType.Response) {
const isResponseStructureOK: boolean = this.helper.validateServerResponseStructure(ev.body);
if (isResponseStructureOK) {
const response: ServerResponseAPI = ev.body;
subject.next(new Result(response.result, response['additional-info']));
} else {
subject.next(new Result(messages.error, messages.invalidStructureOfResponse));
}
}
},
(error: ServerResponseAPI) => {
const errorMessage: string = this.helper.userFriendlyErrorMessage(error);
subject.next(new Result(messages.error, errorMessage));
},
() => { // observable complete
});
}
editAnswer(answer: Answer): any {
const observable = this.bs.editAnswer(answer)
this.subscribeToReturnedObservable(observable,this.editAnswerSubject);
}
到目前为止我写的测试是>
describe('subscribeToReturnedObservable tests:', () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [QuestionManagementService, HelperService, WebToBackendInterfaceService, AuthService, HttpClient, HttpHandler] }); }); fit('should call send next value for the subject is the response from the server is ok', () => { const questionService:QuestionManagementService = TestBed.get(QuestionManagementService); const body = {"result":"success", "additional-info":"some additional info"}; const receivedHttpEvent = new HttpResponse({body:body}); let observable = new Observable(); spyOn(observable,'subscribe').and.returnValue(receivedHttpEvent); spyOn(questionService['editQuestionSubject'],'next'); questionService.subscribeToReturnedObservable(observable,questionService['editQuestionSubject']); observable.subscribe(); expect(questionService['editQuestionSubject'].next).toHaveBeenCalled(); }); });
但收到错误
Expected spy next to have been called.
我创建了此函数,因为对于我的应用程序使用http.post发送的所有请求,这是不同部分处理响应的方式。因此,我不想复制代码,而是想到...
我做到了(希望这是正确的方法)。测试的范围是检查Subject
的next
是否正确调用。因此,请使用Observable
创建一个of
,然后让代码从那里流动。