如何在jasmine中使用真实连接注入HTTP



如何使用真实后端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")
          })
      })));
  });

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

多谢! !

从RC.5开始,您必须使用TestBed。配置你的模块。

所以在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');
  }));
});

你需要使用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
  }));
});

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

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

最新更新