如何在Angular2

时间:2016-07-22 12:09:23

标签: unit-testing http angular

我需要测试这项服务:

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

});

但是,数据无法记录。 我尝试了在SO或互联网上找到的各种解决方案。

其中一个是对mockbackend进行http调用,但这只是给了我data = undefined。

1 个答案:

答案 0 :(得分:3)

您需要注入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