如何使用真实连接在茉莉花中注入HTTP

时间:2016-09-10 21:09:11

标签: unit-testing angular typescript jasmine karma-jasmine

如何使用带有真实后端的http注入实现茉莉花测试?

我的意思是我想使用真正的http连接来测试我的服务

import { provide }                                               from '@angular/core';
import{ClassCall} from 'xx.xx'

import {HTTP_PROVIDERS, XHRBackend, Http} from "@angular/http";
import {MockBackend} from "@angular/http/testing/mock_backend";
import {beforeEachProviders} from "@angular/core/testing/testing";
import {inject} from "@angular/core/testing/test_injector";
import {async} from "@angular/core/testing/async";



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

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

        myCall.Call("hey", "there")
          .then((response)=>{
            expect(response).toBe("anyResponse")
          })
      })));
  });

我还没有看到任何关于它的话题......

非常感谢!!!!!

3 个答案:

答案 0 :(得分:0)

自RC.5起,您必须使用TestBed.configureTestingModule来配置模块。

因此,在beforeEachProviders的测试用例中,您必须使用它,例如:

class HttpMock {
    post(url, content, requestOptions) {
      return {
        toPromise() {
          return Promise.resolve(url);
        }
      }
    }

  }


describe('HttpService Tests', () => {
  let countryMock = new CountryMock();
  let navigationMock = new NavigationServiceMock();
  let httpMock = new HttpMock();
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        {provide: Http, useValue: httpMock},
        {provide: CountryService, useValue: countryMock},
        {provide: NavigationService, useValue: navigationMock},
        AuthService
      ]
    });
  });
  it('should check canActivate and set country de/login', inject([AuthService], (auth: AuthService) => {
    expect(auth).toBeTruthy();
    spyOn(countryMock, "getCountry").and.returnValue({code: 'de'});
    spyOn(auth, "isLoggedIn").and.returnValue(false);
    spyOn(navigationMock, "navigateByUrl").and.callThrough();
    expect(auth.canActivate()).toBeFalsy();
    expect(auth.isLoggedIn).toHaveBeenCalled();
    expect(navigationMock.navigateByUrl).toHaveBeenCalledWith('de/login');
  }));
});

答案 1 :(得分:0)

编辑:在rc.4中你需要使用addProviders

实例https://plnkr.co/edit/XhIkgR92oHRH4rIotXCj?p=preview

import {addProviders, inject} from '@angular/core/testing';
import {MyService} from './myservice';

describe('my code', () => {
  beforeEach(() => {
    addProviders([MyService]);
  });

  it('does stuff', inject([MyService], (service) => {
    // actual test
  }));
});

答案 2 :(得分:0)

正如igorzg所说,rc4中的正确方法是

beforeEach(() => {
    addProviders([MyService, Http, ConnectionBackend, HTTP_PROVIDERS, XHRBackend]);
});