Я тестирую AuthService
, который отправляет информацию для входа пользователя на сервер, используя другой HelperService
.
public authServiceSigninUser(user:UserSigninInfo):any{
console.log('In authServiceSigninUser. contacting server at '+this.API_URL +this.SIGNIN_USER_URL +" with user data "+user+ " with httpOptions "+httpOptions.withCredentials + ","+httpOptions.headers ); //TODOM password should be sent in encrypted format.
let signinInfo= new UserSigninAPI(user);
let body = JSON.stringify(signinInfo);
return this.helperService.sendMessage(this.SIGNIN_USER_URL,body,httpOptions)
}
Я пытаюсь протестировать метод authServiceSigninUser
следующим образом, но когда я запускаю спецификацию,Я получаю ошибку TypeError: Cannot read property 'subscribe' of undefined
.Кажется, что Observable
. Почему?Спецификация теста:
describe('authServiceSigninUser test suite',()=>{
beforeEach(()=>{
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [AuthService, HelperService]
});
});
fit('should sign in user',()=>{
let spy:any;
let helper = TestBed.get(HelperService);
console.log("helper services is ",helper);
let authService = TestBed.get(AuthService);
console.log("auth services is ",authService);
let userSignIn = new UserSigninInfo("test@test.com","test");
let httpMock = TestBed.get(HttpTestingController);
spyOn(helper,'sendMessage');
const responseData = { result: 'success', ['additional-info']: 'login success' };
let httpEvent:HttpResponse<any> = new HttpResponse<any>({body:responseData});
let observable:Observable<HttpEvent<any>> = authService.authServiceSigninUser(userSignIn);
console.log("observable ",observable);//this is undefined
let subscription = observable.subscribe((event)=>{ //error here
console.log('event from authService',event);
});
const mockReq:TestRequest = httpMock.expectOne(environment.apiUrl+environment.signinUserUrl); //Expect that a single request has been made which matches the given URL, and return its mock
//once mocking of sending request is done, mock receiving a response. This will trigger the logic inside subscribe function
mockReq.flush(httpEvent); //flush method provides dummy values as response
httpMock.verify();//verify checks that there are no outstanding requests;
expect(helper.sendMessage).toHaveBeenCalled();
});
});
sendMessage
в HelperService
,
sendMessage(url:string, body:any,httpOptions):Observable<HttpEvent<any>> {
this.loaderService.show();
let observable:Observable<HttpEvent<any>> = this.http.post<any>(url,body,httpOptions);
return observable.pipe(
tap((httpEvent:HttpEvent<any>) => {//tap transparently perform actions or side-effects, such as logging.
if(httpEvent.type === HttpEventType.Response)
{
console.log('response from backend service:', httpEvent);
}
else {
console.log("not an http response")
}
return httpEvent;
})
,catchError(err=>this.handleError(err))
,finalize(()=> this.loaderService.hide()));
}