What is the easiest way to mock the response returned by Http
get()
in Angular 2?
I have local data.json
file in my working directory, and I want get()
to return response containing that data as a payload, simulating the rest api.
Documents for configuring the Backend
object for Http
seemed somewhat obscure and overcomplicated for such a simple task.
You need to override the XhrBackend
provider with the MockBackend
one. You need then to create another injector to be able to execute a true HTTP request.
Here is a sample:
beforeEachProviders(() => {
return [
HTTP_PROVIDERS,
provide(XHRBackend, { useClass: MockBackend }),
SomeHttpService
];
});
it('Should something', inject([XHRBackend, SomeHttpService], (mockBackend, httpService) => {
mockBackend.connections.subscribe(
(connection: MockConnection) => {
var injector = ReflectiveInjector.resolveAndCreate([
HTTP_PROVIDERS
]);
var http = injector.get(Http);
http.get('data.json').map(res => res.json()).subscribe(data) => {
connection.mockRespond(new Response(
new ResponseOptions({
body: data
})));
});
});
}));
By the way, you need to mock the XHRBackend
and provide mocked data in a class with the createDb
method. createDb
method returns the mocked JSON object. To load that data provide correct URL
to http.get
, for example, if JSON object is contained in a variable mockedObject
, then the URL should be "app\mockedObject"
.
You can read more details here: https://angular.io/docs/ts/latest/guide/server-communication.html.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With