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

标签 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) {
    ...
  }

}

这是我的规范文件,它使用 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';

关于unit-testing - 使用 MockBackend 测试然后调用 .map 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39491184/

相关文章:

javascript - 开 Jest 错误意外的 token ...(ES6)

unit-testing - Grails测试 mock For java.util.Calendar.getInstance()

javascript - 让 karma 测试看起来更好(或者更像 rspec)

angular - Svg 并不总是显示

Angular POST 请求不起作用

angular - 类型 'map' 上不存在属性 'Observable<Blob>'

javascript - dotnet new Angular - dist 没有更新?

单元测试私有(private)方法 : Facade pattern

Typescript/Angular2 http.post 不设置标题

reactjs - useReducer 的 initialState 类型为 never?