我有一个LoaderService
export class LoaderService {
private loaderSubject = new Subject<boolean>();
loaderState = this.loaderSubject.asObservable();
constructor() { }
show(){
console.log("showing progress bar");
this.loaderSubject.next(true)
}
hide(){
console.log("Hiding progress bar");
this.loaderSubject.next(false);
}
}
我正在从show
中定义的LoaderService
函数调用sendMessage
的方法HelperService
sendMessage(url:string, body:any,httpOptions):Observable<HttpEvent<any>> {
this.loaderService.show(); //HERE
let observable:Observable<HttpEvent<any>> = this.http.post(url,body,{ headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
withCredentials: true,
observe: 'events', //what post should observe (look for). Here it means events. This could be body as well
responseType: 'json' //responseType tells post how to interpret the body
});
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()));
}
我为spec
写了sendMessage
describe('sendMessage function test suite: ',()=> {
let spy:any;
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'}),
withCredentials: true,
observe: 'events',
responseType: 'json'
};
beforeEach(() => {
TestBed.configureTestingModule({
providers: [HelperService, HttpClient, HttpHandler,LoaderService],
imports: [ReactiveFormsModule, HttpClientModule, HttpClientTestingModule]
});
});
fit('should return HttpEvent',
inject([HttpTestingController,HelperService,HttpClient,LoaderService],(loader:LoaderService, httpClient:HttpClient,httpMock:HttpTestingController)=>{
const responseData = { result: 'success', ['additional-info']: 'some data from server' };
spyOn(loader,'show');
let helperService = new HelperService(loader, httpClient);
let result:Observable<HttpEvent<any>> = helperService.sendMessage('/someURL','someBody',httpOptions);
let subscription = result.subscribe((event:HttpEvent<any>)=>{
console.log('got response ',event);
expect(event).toBeTruthy();
});
expect(loader.show).toHaveBeenCalled();
const mockReq = httpMock.expectOne('/someURL');
expect(mockReq.cancelled).toBeFalsy();
expect(mockReq.request.responseType).toEqual('json');
mockReq.flush(responseData);
httpMock.verify();
}));
});
运行规范时,出现错误
Error: <spyOn> : show() method does not exist
Usage: spyOn(<object>, <methodName>)
我可能做错了什么?