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

时间:2016-09-14 13:03:11

标签: unit-testing angular typescript jasmine angular2-testing

我正在尝试为我的服务编写单元测试,这会产生Http请求。

我的服务返回Http.get()请求,后跟.map()。我无法让我的模拟后端返回.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) {
    ...
  }

}

这是我的spec文件,它使用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();
    }
  )
  });
});

1 个答案:

答案 0 :(得分:2)

您需要导入rxjs,以便使用map

import 'rxjs/Rx';

或者,您只能导入map运算符,因此您的应用不会加载您不会使用的文件:

import 'rxjs/add/operator/map';