Testing using HTTP

Let's start by creating a users.serviceHttp.ts file:

// users.serviceHttp.tsexport class UsersServiceHttp {constructor(private http:Http) { }get(){return this.http.get('api/users.json').map(response => response.json());}}

In this case it uses http.get() to fetch the data from a JSON file. We then used Observable.map() to transform the response into the final result using json().

The difference that exists between this test and the previous one is the use of an asynchronous test:

//users.serviceHttp.spec.tsdescribe('Service: UsersServiceHttp', () => {let service;//setupbeforeEach(() => TestBed.configureTestingModule({imports: [ HttpModule ],providers: [ UsersServiceHttp ]}));beforeEach(inject([UsersServiceHttp], s => {

Get TypeScript 2.x for Angular Developers now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.