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

What is the easiest way to dismiss the response returned by Http get() in Angular 2?

I have a local data.json file in my working directory and I want get() return a response containing this data as a payload, simulating the rest of the api.

The documents for setting up the Backend object for Http seemed somewhat obscure and complicated for such a simple task.

+6
source share
3 answers

You need to redefine the XhrBackend provider using MockBackend . Then you need to create another injector in order to make a true HTTP request.

Here is an example:

 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 }))); }); }); })); 
+2
source

By the way, you need to make fun of XHRBackend and provide the scoffed data in the class using the createDb method. The createDb method returns a mocking JSON object. To load this data, return the URL to http.get , for example, if the JSON object is contained in the variable mockedObject , then the URL should be "app\mockedObject" .

You can read more here: https://angular.io/docs/ts/latest/guide/server-communication.html.

+1
source

You can use the HttpTestingController, available through the core of TestBed, as for me it feels more intuitive (each of them, of course). Unconfirmed fragment:

 import { TestBed, async } from '@angular/core/testing'; import { HttpTestingController } from '@angular/common/http/testing'; import { MyApiService } from './my-api.service'; export function main() { describe('Test set', () => { let httpMock: HttpTestingController; beforeEach(() => { TestBed.configureTestingModule({ imports: [], providers: [MyApiService] }); httpMock = TestBed.get(HttpTestingController); }); it('should call get', async(() => { const data: any = {mydata: 'test'}; let actualResponse: any = null; MyApiService.get().subscribe((response: any) => { actualResponse = response; }); httpMock.expectOne('localhost:5555/my-path').flush(data); expect(actualResponse).toEqual(data); })); }); } 
0
source

All Articles