Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a unit test for Http get MockBackend in Angular2?

How to do a unit test for Http get MockBackend in Angular2?

I'm having trouble testing my http unit test. Every time I look at MockBackend it seems confusing, a lot of code and some imports never work.

I just want a very basic http get unit test

I'm using: typescript, angular2, jasmine and karma runner.

My actual code works fine.

Here is my code that I'm testing:

 import {Injectable} from 'angular2/angular2';
 import {HTTP_PROVIDERS, Http, Headers} from 'angular2/http';

 @Injectable()

 export class FirebaseService{
   headers: Headers;

   //Test issue seems to be here when I inject Http instance.
   constructor(public http?: Http) {  
     this.headers = new Headers();
     this.headers.append('Content-Type', 'application/json');
   }

   //This is the method I'm testing.
   public getSpotifyTracks = ():Promise<Object> =>{ 
       return this.http
        .get('https://api.spotify.com/v1/tracks/0eGsygTp906u18L0Oimnem',      {headers:this.headers})
        .map((response) => {
           return response.json()
        }).toPromise();  
   }

 }

Here is my unit test for that code:

import {it, iit, describe, expect, inject, injectAsync, beforeEachProviders, fakeAsync, tick} from 'angular2/testing';
import {HTTP_PROVIDERS, Http, Headers} from 'angular2/http';
import {FirebaseService} from '../app/firebase-service';

describe('Firebase Service Calls', () => {
    beforeEachProviders(()=> [Http, FirebaseService]); 

    //Issue seems to be here????
    it('get all tracks from spotify', injectAsync([FirebaseService],(service) => {      

        return service.getSpotifyTracks().then((response) => {
          expect(response.length).not.toBe(null);
        });   

    }), 3000);

});
like image 621
AngularM Avatar asked Dec 08 '15 17:12

AngularM


3 Answers

First import all modules :

import {it,describe,expect,inject,injectAsync,beforeEachProviders} from 'angular2/testing';
import {provide, Injector} from 'angular2/core';

import {MockBackend} from 'angular2/http/testing';
import {YourServiceToBeTested} from 'path/to/YourServiceToBeTested';

Next you need to declare the Mocked HttpBackend :

describe('Service with Http injected', () => {
beforeEachProviders(() => {
[
  MockBackend,
  BaseRequestOptions,
  provide(
      Http,
         {
            useFactory: (backend, defaultOptions) => {
              return new Http(backend, defaultOptions);
       },
       deps: [MockBackend, BaseRequestOptions]
  }),
  YourServiceToBeTested
]
});

Finally on each test, you need to inject the mock & set the mocked value (ie the fake data returned by your service for this specific test)

it('should respect your expectation',

inject(
  [YourServiceToBeTested, MockBackend],
  (yourServiceToBeTested, mockBackend) => {

    let response = 'Expected Response from HTTP service usually JSON format';
    let responseOptions = new ResponseOptions({body: response});
mock.connections.subscribe(
    c => c.mockRespond(new Response(responseOptions)));

    var res = yourServiceToBeTested.ServiceMethodToBeTest(serviceParams);
    expect(res).toEqual('your own expectation');
  }));
like image 126
f-del Avatar answered Nov 13 '22 10:11

f-del


While @f-del s answer gets the same result this is easier and uses Angulars DI better.

describe('Firebase Service Calls', () => {
    beforeEachProviders(()=> [
        HTTP_PROVIDERS,
        MockBackend,
        provide(XHRBackend, {useExisting: MockBackend})]);

This way, when Http is requested, and instance that uses MockBackend is provided.

like image 27
Günter Zöchbauer Avatar answered Nov 13 '22 10:11

Günter Zöchbauer


In Angular 2.2.1 provide does not exist in core anymore , so we should do :

{
    provide : Http,
    deps : [ MockBackend, BaseRequestOptions ],
    useFactory : ( backend : MockBackend, defaultOptions : BaseRequestOptions ) => {
        return new Http( backend, defaultOptions );
    }
}
like image 2
Milad Avatar answered Nov 13 '22 09:11

Milad