nottinhill nottinhill - 2 months ago 54
TypeScript Question

How to Test Angular2 / TypeScript HTTPService without Mock

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';

@Injectable()
export class HttpService {
result: any;

constructor(private http:Http) {
}

public postRequest(){
return this.http.get('http://httpbin.org/get');
}
}


Above is my code, here is my Test:

I do not want to mock anything, just test the real http connection.

Edit - New service.spec file:



import {beforeEachProviders, beforeEach, it, describe, expect, inject} from '@angular/core/testing';
import {HttpService} from '../../providers/http-service/http-service';
import {TranslateService} from 'ng2-translate/ng2-translate';
import {Goal} from '../../providers/goal/goal';
import {NavController} from 'ionic-angular';
import {HTTP_PROVIDERS, Http} from '@angular/http';

describe('Http Service Test', () => {

beforeEachProviders(() => {
return [
HTTP_PROVIDERS,
HttpService
];
});

it('should return response when subscribed to postRequest',
inject([HttpService], (httpService: HttpService) => {

httpService.postRequest().subscribe((res) => {
expect(res.text()).toBe('hello raja');
});
}));
});


These are my errors in karma console:

28 06 2016 14:33:32.067:ERROR [Chrome 51.0.2704 (Mac OS X 10.11.4) | Http Service Test | should return response when subscribed to postRequest]: TypeError: Cannot read property 'getCookie' of null
at CookieXSRFStrategy.configureRequest (http://localhost:9876/absolute/var/folders/vy/18sb1wqs60g734bhr75cw9_r0000gn/T/9b9439f5f9c1590d3052594bcae9e877.browserify?26719cf22e6406ebc638b6b187c777666dcc5698:36568:81)
at XHRBackend.createConnection (http://localhost:9876/absolute/var/folders/vy/18sb1wqs60g734bhr75cw9_r0000gn/T/9b9439f5f9c1590d3052594bcae9e877.browserify?26719cf22e6406ebc638b6b187c777666dcc5698:36583:28)
at httpRequest (http://localhost:9876/absolute/var/folders/vy/18sb1wqs60g734bhr75cw9_r0000gn/T/9b9439f5f9c1590d3052594bcae9e877.browserify?26719cf22e6406ebc638b6b187c777666dcc5698:37476:20)

Answer

You need first to configure providers for the mock HTTP backend:

describe('HttpService Tests', () => {
  beforeEachProviders(() => {
    return [
      HTTP_PROVIDERS,
      provide(XHRBackend, { useClass: MockBackend }),
      HttpService
   ];
});

Then you can use the mock backend this way:

mockBackend.connections.subscribe(
  (connection: MockConnection) => {
    if (connection.request.url === 'file1.json') {
      // Simulate an error
      var err = new ResponseError();
      err.status = 404;
      connection.mockError(<Error>err);
    } else {
      // Simulate a successful response
      connection.mockRespond(new Response(
        new ResponseOptions({
          body: ['i love angular2']
        })));
    }
  });

httpService.postRequest().subscribe((res:Respsone) => {
  expect(res.text()).toBe('hello raja');
});

Edit

If you want to test with real connection, use the classical HTTP_PROVIDERS only:

describe('HttpService Tests', () => {
  beforeEachProviders(() => {
    return [
      HTTP_PROVIDERS,
      HttpService
   ];
});

Edit1

Since your call is asynchronous, you could use async:

it('should return response when subscribed to postRequest',
    async(inject([HttpService], (httpService: HttpService) => {

        httpService.postRequest().subscribe((res) => {
            expect(res.text()).toBe('hello raja');
        }); 
})));