AngularM
AngularM

Reputation: 16628

I want to do a basic angular 2 unit test for a http get request

My tech: angular version 4, webpack, karma, unit tests in jasmine and typescript.

I want a basic example of how I test my service function that has a http call.

This is my basic service:

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

@Injectable()

export class TestService {
    headers: Headers;
    http: Http;

    constructor(http: Http) {
        this.http = http;
        this.headers = new Headers();
    }

    test = (): Promise<boolean> => {
        return new Promise((resolve, reject) => {
            const url = 'http://www.ipsumlorem.com/json';

            this.http.request(url).subscribe(response => {
                resolve(true);
            });
        });
    }
};

This is my current spec (unit test) for it:

import { TestService } from './test.service';

import {Injectable, ReflectiveInjector} from '@angular/core';
import {async, fakeAsync, tick, inject, TestBed} from '@angular/core/testing';
import {BaseRequestOptions, ConnectionBackend, Http, ResponseOptions, Response, HttpModule} from '@angular/http';
import {MockBackend, MockConnection} from '@angular/http/testing';

let service;

describe('Service : testService', () => {

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
          TestService,
          MockBackend,
          BaseRequestOptions,
          {
            provide: Http,
            deps: [MockBackend, BaseRequestOptions],
            useFactory: (mb:MockBackend, opts:BaseRequestOptions) => {
              return new Http(mb, opts);
            }
          }
      ],
      imports: [HttpModule]
      }).compileComponents();
  });

  beforeEach(inject([Http], (http: Http) => {
     service = new TestService(http);
  }));

  it('should call test function and return a promise with value true', async(() => {
      //Mock response
      TestBed.get(MockBackend).connections.subscribe(c => {
        c.mockRespond(new Response(new ResponseOptions({body: Promise.resolve(true)})));
      });

      let result = true;
      service.test().then((response: any) => result);
      expect(result).toEqual(true);
  }));

});

Upvotes: 1

Views: 712

Answers (1)

The Head Rush
The Head Rush

Reputation: 3357

Working example:

import { TestService } from './test.service';

import {Injectable, ReflectiveInjector} from '@angular/core';
import {async, fakeAsync, tick, inject, TestBed} from '@angular/core/testing';
import {BaseRequestOptions, ConnectionBackend, Http, ResponseOptions, Response, HttpModule} from '@angular/http';
import {MockBackend, MockConnection} from '@angular/http/testing';

let service;

describe('Service : testService', () => {

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
          TestService,
          MockBackend,
          BaseRequestOptions,
          {
            provide: Http,
            deps: [MockBackend, BaseRequestOptions],
            useFactory: (mb:MockBackend, opts:BaseRequestOptions) => {
              return new Http(mb, opts);
            }
          }
      ],
      imports: [HttpModule]
      }).compileComponents();
  });

  beforeEach(inject([Http], (http: Http) => {
     service = new TestService(http);
  }));

  it('should call test function and return a promise with value true', async(() => {
      //Mock http call
      TestBed.get(MockBackend).connections.subscribe(c => {
        c.mockRespond(new Response(new ResponseOptions({body: Promise.resolve(true)})));
      });

      service.test().then((response: any) => {
        expect(response).toEqual(true);
      }); 
  }));    
});

Upvotes: 2

Related Questions