Search code examples
angularangular2-services

Angular 2 unit test http.get undefined


I am trying to write the angular 2 unit test for async http service using MockBackend but getting http.get undefined error. Here is my code:

Http Service:

import { Injectable } from '@angular/core';
import { Http,Headers,RequestOptions,Response } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';

@Injectable()
export class HttpService {


    constructor(private _http: Http) {}

    /**
     *  Http request will time out if not received response within 20 sec
     * 
     * @param url
     * @returns {Observable<R>}
     */
    getData(url : string) {
        return this._http.get(url)
            .timeout(20000, new Error('delay exceeded'))
            .map(response => response.json());
    }

}

My Custom component method for which I am writing unit test:

 private loadDetails(input : string){
        this._httpService.getData("/api/test"+ input)
            .subscribe(
                data => {this.user = data,
                         // Some more logic in here based on data     
                },
                error =>  { console.log( error);}
            );
    }

Unit Test :

import { HttpService } from "../shared/services/http.service";
import {
    async,
    inject,
    fakeAsync,
    TestBed
} from '@angular/core/testing';

import {
Http,
    BaseRequestOptions,
    Response,
    BaseResponseOptions,
    ResponseOptions
} from '@angular/http';

import { HttpModule } from '@angular/http';

import {
    MockBackend,
    MockConnection
} from '@angular/http/testing';
import { Observable } from 'rxjs/Rx';

import { TestingComponent } from './testing.component';

const mockHttpProvider = {
    deps: [ MockBackend, BaseRequestOptions ],
    useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => {
        return new Http(backend, defaultOptions);
    }
}

describe('testingComponent', () => {

    let fixture,testingComponent;

    // provide our implementations or mocks to the dependency injector
    beforeEach(() => {

        TestBed.configureTestingModule({
            declarations: [
                CustomComponent
            ],
            providers: [
                HttpService,
                MockBackend,
                BaseRequestOptions,
                {provide: Http, useValue: mockHttpProvider}
            ]
        });

        fixture = TestBed.createComponent(PortfolioComponent);
        testingComponent = fixture.debugElement.componentInstance;
    });


    it('should call loadDetails to load user details',  inject(
        [IPIQHttpService, MockBackend],
        fakeAsync((service: HttpService, backend: MockBackend) => {
            backend.connections.subscribe((connection: MockConnection) => {

                let mockResponseBody= {
                    id: '123',
                    title: 'test',
                    empno: '456'
                };

                let response = new ResponseOptions({body: JSON.stringify(mockResponseBody)});
                connection.mockRespond(new Response(response));
            });
            testingComponent.loadUserDetails('123');
            expect(testingComponent.user.empno).toEqual('456');
        })));


});

when I am calling testingComponent.loadUserDetails('123') to call the http service , I am getting http.get method undefined.

Any idea what I am doing wrong here?


Solution

  • Finally it's working. Here are the changes I have made:

    1. Imported HttpModule and changed the way I was using mockHttpProvider as suggested by @ Günter Zöchbauer in previous post:
    const mockHttpProvider =  
    { 
    provide: Http,
     deps: [ MockBackend, BaseRequestOptions ], 
    useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => 
    { return new Http(backend, defaultOptions); } 
    }
    
     TestBed.configureTestingModule({
            imports: [HttpModule], // <<<=== added
            declarations: [
                CustomComponent
            ],
            providers: [
                HttpService,
                MockBackend,
                BaseRequestOptions,
                mockHttpProvider
            ]
        });
    
    1. Changed my unit test and removed fakeAsync:
    it('should call loadDetails to load user details', inject([HttpService, MockBackend, Http], (_httpService, backend, http) => {
            backend.connections.subscribe(connection => {
                let mockResponseBody= {
                     id: '123',
                     title: 'test',
                     empno: '456'
                };
                let response = new ResponseOptions({body: JSON.stringify(mockResponseBody)});
                connection.mockRespond(new Response(response));
            });
            testingComponent.loadDetails('123');
            expect(testingComponent.user.empno).toEqual('456');
        }));