如何在Angular2中使用MockBackend

如何在Angular2中使用MockBackend

本文介绍了如何在Angular2中使用MockBackend的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要测试这项服务:

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()函数,我有这段代码:

To test the getLogin() function I have this code:

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或互联网上找到的各种解决方案。

However, the data doesn't get logged.I tried various solutions that I found on SO or on the internet.

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

One of them was to make a http call to the mockbackend but that just gave me data = undefined.

推荐答案

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

You need to inject MockBackend and subscribe for connection, like this:

UPDATE

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

详情请点击此处:

这篇关于如何在Angular2中使用MockBackend的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 08:51