3
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)
2
  • 1
    if you are testing beyond the boundaries of your classes and reaching other external services is not an unit test, probably you want an Integration test. Commented Jun 28, 2016 at 12:55
  • 1
    It is legitimate to construct integration testing through a unit testing framework. Commentators please provide answer rather than banging with unit testing and mock. Commented Jul 2, 2016 at 21:19

2 Answers 2

2

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');
        }); 
})));
Sign up to request clarification or add additional context in comments.

8 Comments

Ok I updated my Question with new code from your reply. Can you confirm that is working? (I still get bundle errors in karma)
Which version of Angular2 do you use? Perhaps you could use async... I updated my answer accordingly
Latest Version of angular2.(RC1 2.0.0) I am really greatful for your help! I will now test your suggestion. Also see stackoverflow.com/questions/34987391/…
Ok with the Link I posted, the test is now passing, but my "res" / result is empty. Any ideas? And any luck with RC3?
I would debug your test. I mean start karma without the singleRun option set to true and click on the debug button in the browser. Then you can add breakpoints in both service and test to see the HTTP request...
|
1

See https://angular.io/docs/ts/latest/api/http/testing/MockBackend-class.html

import {BaseRequestOptions, Http} from '@angular/http';
import {MockBackend} from '@angular/http/testing';
it('should get some data', inject([AsyncTestCompleter], (async) => {
  var connection;
  var injector = Injector.resolveAndCreate([
    MockBackend,
    {provide: Http, useFactory: (backend, options) => {
      return new Http(backend, options);
    }, deps: [MockBackend, BaseRequestOptions]}]);
  var http = injector.get(Http);
  var backend = injector.get(MockBackend);
  //Assign any newly-created connection to local variable
  backend.connections.subscribe(c => connection = c);
  http.request('data.json').subscribe((res) => {
    expect(res.text()).toBe('awesome');
    async.done();
  });
  connection.mockRespond(new Response('awesome'));
}));

and https://angular.io/docs/ts/latest/api/http/testing/MockConnection-class.html

var connection;
backend.connections.subscribe(c => connection = c);
http.request('data.json').subscribe(res => console.log(res.text()));
connection.mockRespond(new Response(new ResponseOptions({ body: 'fake response' }))); //logs
'fake response'

3 Comments

No, No I expicity NO NOT want to mock... ;D
What's the problem then? If you don't mock Http then it's not an unit test but an integration test.
My code has some basic TypeScript / Angular2 malunderstandings. I do not know which. I can plunkr this for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.