我想为http get请求进行基本的角度2单元测试

时间:2017-04-18 15:19:28

标签: unit-testing angular

我的技术:角度版本4,webpack,业力,茉莉花和打字稿中的单元测试。

我想要一个基本的例子,说明我如何测试具有http调用的服务函数。

这是我的基本服务:

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);
            });
        });
    }
};

这是我目前的规格(单元测试):

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);
  }));

});

1 个答案:

答案 0 :(得分:2)

工作示例:

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);
      }); 
  }));    
});