mardi 8 décembre 2015

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

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

I'm having trouble testing my http unit test. I'm using: typescript, angular2, jasmine and karma runner.

My tests seem to fail because when I make an instance of my service I need to include the Http instance and I'm not sure how to do that.

My actual code works fine. I just need to know how to test with Http inject into the constructor in order to call my method to test it.

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('http://ift.tt/1XZtY2o',      {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);

});

Aucun commentaire:

Enregistrer un commentaire