使用 MockBackend 测试然后调用 .map 的函数

using MockBackend to test function that then calls .map

我正在尝试为发出 Http 请求的服务编写单元测试。

我有一项服务 return 是 Http.get() 请求后跟 .map()。我无法将我的模拟后端设置为 return,但在 .map() 上不会出错。我得到的错误是:

this._http.get(...).map is not a function

我一直在使用 this article 作为我的主要指南。

如果我从我的服务函数中删除 .map(),我不会收到任何错误。我怎样才能让我的模拟响应有一个我可以调用的 .map() 函数?

注意:我目前使用的是RC.4

这是我的服务:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import { AppSettings } from '../../../settings';
import { Brand } from '../../models/index';

@Injectable()
export class BrandDataService {

  allBrands : Brand[];
  groups : any;
  groupNames : string[];

  constructor (
    private _http : Http
  ) {}

  /**
  * Get all brands
  */
  public getAllBrands () :Observable<any> {

    let url = AppSettings.BRAND_API_URL + 'brands';
    return this._http.get( url )
    .map( this.createAndCacheBrands )
    .catch( (error) => {
      return Observable.throw( error );
    });        
  }

  private createAndCacheBrands (res:Response) {
    ...
  }

}

这是我的规范文件,它使用 MockBackend 和其他相关库来模拟这些测试的后端:

// vendor dependencies
import { Http, BaseRequestOptions, Response, ResponseOptions, RequestMethod } from '@angular/http';
import { addProviders, inject } from '@angular/core/testing';
import { MockBackend, MockConnection } from '@angular/http/testing';

// Service to test
import { BrandDataService } from './brandData.service';


describe( 'Brand data service', () => {

  let service : BrandDataService = null;
  let backend : MockBackend = null;

  // Provide a mock backend implementation
  beforeEach(() => {
    addProviders([
      MockBackend,
      BaseRequestOptions,
      {
        provide : Http,
        useFactory : (backendInstance : MockBackend, defaultOptions : BaseRequestOptions) => {
          return new Http(backendInstance, defaultOptions);
        },
        deps : [MockBackend, BaseRequestOptions]
      },
      BrandDataService
    ])
  })

  beforeEach (inject([BrandDataService, MockBackend], (_service : BrandDataService, mockBackend : MockBackend) => {
    service = _service;
    backend = mockBackend;
  }));

  it ('should return all brands as an Observable<Response> when asked', (done) => {
    // Set the mock backend to respond with the following options:
backend.connections.subscribe((connection : MockConnection) => {
    // Make some expectations on the request
  expect(connection.request.method).toEqual(RequestMethod.Get);
    // Decide what to return
    let options = new ResponseOptions({
      body : JSON.stringify({
        success : true
      })
    });
    connection.mockRespond(new Response(options));
  });

  // Run the test.
  service
  .getAllBrands()
  .subscribe(
    (data) =>  {
      expect(data).toBeDefined();
      done();
    }
  )
  });
});

您需要导入 rxjs 才能使用 map:

import 'rxjs/Rx';

或者,您可以只导入 map 运算符,这样您的应用就不会加载您不会使用的文件:

import 'rxjs/add/operator/map';