Angular Experts,
I'm unit testing my application and I'm experimenting a little.
Specifically I'd like to unit test the Components with the real Services by just mocking the Http object. Right now I'm trying to stub the object by myself so I made the StubHttp class below.
Angular 2: verson 2.4.7 + Karma, Jasmine.
this is its simplified version:
let mockTest = '{"name":'John', // ...};
export class StubHttp {
public post(url: string, body: any, options?: RequestOptionsArgs)
:Observable<Response> {
let response = new ResponseOptions({body: JSON.stringify(mockTest)});
return Observable.of(new Response(response));
}
}
If I put a log in my controller:
this.UsersService.getAll().subscribe(( data: any ) => {
console.log('data = ', data);
});
and the service:
getAll( event: LazyLoadEvent) {
return this.http.post( this.url + this.params, JSON.stringify( this.body ),new RequestOptions({headers: this.header}) )
.map( response => response.json() )
.catch( this.handleError );
}
this is the output:
LOG: 'data = ', Promise{}
where is the mistake?
I solved by using XHRBackend and mockBackend instead of my Http Stub.
it('Should show a list of 10 feed',
inject([XHRBackend], (mockBackend) => {
mockBackend.connections.subscribe((connection) => {
connection.mockRespond(new Response(new ResponseOptions({
body: {id: 55}
})));
});
// ...
}));
https://blog.thoughtram.io/angular/2016/11/28/testing-services-with-http-in-angular-2.html