Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 mock Http get() to return local json file

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.

like image 889
Tuomas Toivonen Avatar asked May 30 '16 13:05

Tuomas Toivonen


2 Answers

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
          })));
      });
    });
}));
like image 156
Thierry Templier Avatar answered Nov 08 '22 15:11

Thierry Templier


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.

like image 1
Anoush Hakobyan Avatar answered Nov 08 '22 14:11

Anoush Hakobyan