如何在没有模拟的情况下测试Angular2 / TypeScript HTTPService

时间:2016-06-28 12:08:28

标签: testing typescript angular integration-testing

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

@Injectable()
export class HttpService {
  result: any;

  constructor(private http:Http) {
  }

   public postRequest(){
       return this.http.get('http://httpbin.org/get');    
  }
}

以上是我的代码,这是我的测试:

不想模拟 ,只需测试真实的http连接。

编辑 - 新的service.spec文件:

import {beforeEachProviders, beforeEach, it, describe, expect, inject} from '@angular/core/testing';
import {HttpService} from '../../providers/http-service/http-service';
import {TranslateService} from 'ng2-translate/ng2-translate';
import {Goal} from '../../providers/goal/goal';
import {NavController} from 'ionic-angular';
import {HTTP_PROVIDERS, Http} from '@angular/http';

describe('Http Service Test', () => {

      beforeEachProviders(() => {
        return [
            HTTP_PROVIDERS,
            HttpService
        ];
    });

    it('should return response when subscribed to postRequest',
        inject([HttpService], (httpService: HttpService) => {

            httpService.postRequest().subscribe((res) => {
                expect(res.text()).toBe('hello raja');
            }); 
    }));
});

这些是我在karma控制台中的错误:

28 06 2016 14:33:32.067:ERROR [Chrome 51.0.2704 (Mac OS X 10.11.4) | Http Service Test | should return response when subscribed to postRequest]: TypeError: Cannot read property 'getCookie' of null
    at CookieXSRFStrategy.configureRequest (http://localhost:9876/absolute/var/folders/vy/18sb1wqs60g734bhr75cw9_r0000gn/T/9b9439f5f9c1590d3052594bcae9e877.browserify?26719cf22e6406ebc638b6b187c777666dcc5698:36568:81)
    at XHRBackend.createConnection (http://localhost:9876/absolute/var/folders/vy/18sb1wqs60g734bhr75cw9_r0000gn/T/9b9439f5f9c1590d3052594bcae9e877.browserify?26719cf22e6406ebc638b6b187c777666dcc5698:36583:28)
    at httpRequest (http://localhost:9876/absolute/var/folders/vy/18sb1wqs60g734bhr75cw9_r0000gn/T/9b9439f5f9c1590d3052594bcae9e877.browserify?26719cf22e6406ebc638b6b187c777666dcc5698:37476:20)

2 个答案:

答案 0 :(得分:2)

首先需要为模拟HTTP后端配置提供程序:

describe('HttpService Tests', () => {
  beforeEachProviders(() => {
    return [
      HTTP_PROVIDERS,
      provide(XHRBackend, { useClass: MockBackend }),
      HttpService
   ];
});

然后你可以这样使用模拟后端:

mockBackend.connections.subscribe(
  (connection: MockConnection) => {
    if (connection.request.url === 'file1.json') {
      // Simulate an error
      var err = new ResponseError();
      err.status = 404;
      connection.mockError(<Error>err);
    } else {
      // Simulate a successful response
      connection.mockRespond(new Response(
        new ResponseOptions({
          body: ['i love angular2']
        })));
    }
  });

httpService.postRequest().subscribe((res:Respsone) => {
  expect(res.text()).toBe('hello raja');
});

修改

如果您想使用真实连接进行测试,请仅使用经典的HTTP_PROVIDERS:

describe('HttpService Tests', () => {
  beforeEachProviders(() => {
    return [
      HTTP_PROVIDERS,
      HttpService
   ];
});

<强> EDIT1

由于您的呼叫是异步的,因此您可以使用async

it('should return response when subscribed to postRequest',
    async(inject([HttpService], (httpService: HttpService) => {

        httpService.postRequest().subscribe((res) => {
            expect(res.text()).toBe('hello raja');
        }); 
})));

答案 1 :(得分:1)

请参阅https://angular.io/docs/ts/latest/api/http/testing/MockBackend-class.html

import {BaseRequestOptions, Http} from '@angular/http';
import {MockBackend} from '@angular/http/testing';
it('should get some data', inject([AsyncTestCompleter], (async) => {
  var connection;
  var injector = Injector.resolveAndCreate([
    MockBackend,
    {provide: Http, useFactory: (backend, options) => {
      return new Http(backend, options);
    }, deps: [MockBackend, BaseRequestOptions]}]);
  var http = injector.get(Http);
  var backend = injector.get(MockBackend);
  //Assign any newly-created connection to local variable
  backend.connections.subscribe(c => connection = c);
  http.request('data.json').subscribe((res) => {
    expect(res.text()).toBe('awesome');
    async.done();
  });
  connection.mockRespond(new Response('awesome'));
}));

https://angular.io/docs/ts/latest/api/http/testing/MockConnection-class.html

var connection;
backend.connections.subscribe(c => connection = c);
http.request('data.json').subscribe(res => console.log(res.text()));
connection.mockRespond(new Response(new ResponseOptions({ body: 'fake response' }))); //logs
'fake response'