我有这项服务我需要测试:

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

@Injectable()
export class LoginService {

  private baseUrl: string = 'http://localhost:4000/';

  constructor (private http: Http) {}

  public getBaseUrl() {
    return this.baseUrl;
  }

  getLogin() {
    return this.http.get(this.baseUrl + 'api/auth/octopus')
      .map(res => res.json().redirect);
  }
}

要测试getlogin()函数,我有以下代码:
import {
  async,
  describe,
  it,
  expect,
  beforeEach,
  addProviders,
  inject
} from '@angular/core/testing';
import { provide} from '@angular/core';
import { LoginService } from './login.service';
import {
  Http,
  BaseRequestOptions,
} from '@angular/http';
import {MockBackend} from '@angular/http/testing';


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

  beforeEach(() => addProviders([
    LoginService,
    BaseRequestOptions,
    MockBackend,
    provide(Http, {
      useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => {
        return new Http(backend, defaultOptions);
      },
      deps: [MockBackend, BaseRequestOptions]
    })
  ]));

  it('should return data.',
    async(inject([LoginService], (loginService: LoginService) => {
      loginService.getLogin().subscribe(
        data => console.log(data)
      );
    })
  ));

});

但是,数据不会被记录下来。
我尝试了各种各样的解决方案,我发现在某某或互联网上。
其中一个是对mockbackend进行http调用,但这只是给了我data=undefined。

最佳答案

您需要注入mockbackend并订阅连接,如下所示:
更新

async(inject([LoginService, MockBackend], (loginService: LoginService, mockBackend:MockBackend) => {
  let mockResponse = new Response(new ResponseOptions({body: {'redirect': 'some string'}}))
  mockBackend.connections.subscribe(c => c.mockRespond(mockResponse));
  loginService.getLogin().subscribe(
    data => console.log(data)
  );
})

有关详细信息,请访问:
https://angular.io/docs/ts/latest/api/http/testing/index/MockBackend-class.html

09-27 18:14