在服务调用中未定义回调参数。茉莉花单元测试失败(Angular 2)

时间:2017-02-16 16:56:43

标签: angular unit-testing typescript jasmine

我已经被困在这个2天了。我对一个失败的服务调用进行了单元测试。这是服务代码[nummeasurements.service.ts]:

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map'
import {ServiceConfiguration} from '../../../serviceconfiguration';
import {MeasurementCount} from './measurementcount.model';


@Injectable()
export class NumMeasurementsService {

  private configuration: ServiceConfiguration;
  private numMeasurementsUrl: string;
  private measurementCount: MeasurementCount;


  constructor (private http: Http, configuration: ServiceConfiguration) {
    // console.log(configuration);

    this.numMeasurementsUrl = configuration.baseURL + '/getnumberofmeasurements';
    this.configuration = configuration;
    // console.log("this.numProbesUrl: " + this.numProbesUrl);
  }

  createAuthorizationHeader(headers: Headers) {

    let user = this.configuration.user;
    let apisecret = this.configuration.apiSecret;

    headers.append('X-Auth-Key', user);
    headers.append('X-Auth-Secret', apisecret);
  }


  public getMeasurementCount() : Observable<MeasurementCount> {
    let headers = new Headers();
    this.createAuthorizationHeader(headers);

    return this.http.get(this.numMeasurementsUrl, {headers: headers})
      .map((response:Response) => {
          this.measurementCount = <MeasurementCount>response.json();
          // console.log(response.json());
          }
      )
      .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
  }

}

这是[serviceconfiguration.ts]:

import {Injectable} from '@angular/core';

@Injectable()

export class ServiceConfiguration {

  baseURL: string;
  user: string;
  apiSecret: string;

  constructor() {
    this.baseURL = 'http://localhost:9090';
    this.user = 'mjones010c';
    this.apiSecret = '123e4567-e89b-12d3-a456-426655440000';
  }

}

这是抛出错误的实际规范[nummeasurements.service.spec.ts]:

import {
  TestBed,
  getTestBed,
  async,
  inject
} from '@angular/core/testing';
import {
  Headers, BaseRequestOptions,
  Response, HttpModule, Http, XHRBackend, RequestMethod
} from '@angular/http';

import {ResponseOptions} from '@angular/http';
import {MockBackend, MockConnection} from '@angular/http/testing';

import {NumMeasurementsService} from './nummeasurements.service';
import {MeasurementCount} from "./measurementcount.model";
import {ServiceConfiguration} from "../../../serviceconfiguration";

describe('NumMeasurementsService', () => {
  let mockBackend: MockBackend;

  let serviceConfiguration = new ServiceConfiguration();

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      providers: [
        NumMeasurementsService,
        MockBackend,
        BaseRequestOptions,
        ServiceConfiguration,
        {
          provide: Http,
          deps: [MockBackend, BaseRequestOptions],
          useFactory: (backend: XHRBackend, defaultOptions: BaseRequestOptions) => {
            return new Http(backend, defaultOptions);
          }
        }
      ],
      imports: [
        HttpModule
      ]
    });
    mockBackend = getTestBed().get(MockBackend);
  }));


  it('should be defined', () => {
    let numMeasurementsService: NumMeasurementsService;
    getTestBed().compileComponents();

    numMeasurementsService = getTestBed().get(NumMeasurementsService);
    expect(numMeasurementsService).toBeDefined();

  })

  it('should be defined', () => {
    let numMeasurementsService: NumMeasurementsService;
    getTestBed().compileComponents();

    numMeasurementsService = getTestBed().get(NumMeasurementsService);
    expect(numMeasurementsService).toBeDefined();

  })


  it('should get measurement count', done => {
    let numMeasurementsService: NumMeasurementsService;
  //
    getTestBed().compileComponents().then(() => {
      mockBackend.connections.subscribe(
        (connection: MockConnection) => {
          connection.mockRespond(new Response(
            new ResponseOptions({
                body: {
                  "totalMeasurementCount": 17,
                  "measurementInfo": [
                    {
                      "measurementType": "DNS",
                      "measurementCount": 6
                    },
                    {
                      "measurementType": "Ping",
                      "measurementCount": 11
                    }
                  ]
                }
              }
            )));
        });

      numMeasurementsService = getTestBed().get(NumMeasurementsService);
      expect(numMeasurementsService).toBeDefined();

      numMeasurementsService.getMeasurementCount().subscribe((measurementCount: MeasurementCount) => {

        expect(measurementCount).toBeDefined();
        // expect(measurementCount.totalMeasurementCount).toEqual(17);

        done();
      });
    });
  });
}

此处的测试失败在expect(measurementCount).toBeDefined();:

numMeasurementsService.getMeasurementCount().subscribe((measurementCount: MeasurementCount) => {

    expect(measurementCount).toBeDefined();
    // expect(measurementCount.totalMeasurementCount).toEqual(17);

    done();
  });

这是它正在使用的模拟服务:

import { Observable } from 'rxjs/Observable';
import { MeasurementCount } from './measurementcount.model';

export class NumMeasurementsMockService {

  measurementCount : MeasurementCount; // = new MeasurementCount(3);

  public getMeasurementCount(): Observable<MeasurementCount> {
    return Observable.of(this.measurementCount);
  }

}

这是我从Karma获得的实际错误输出:

Chrome 56.0.2924 (Mac OS X 10.10.5) NumMeasurementsService should get measurement count FAILED
    Expected undefined to be defined.
        at SafeSubscriber._next (webpack:///src/app/dashboard/infobox/nummeasurements/nummeasurements.service.spec.ts:98:33 <- src/test.ts:90347:42) [ProxyZone]
        at SafeSubscriber.__tryOrSetError (webpack:///~/rxjs/Subscriber.js:232:0 <- src/test.ts:644:16) [ProxyZone]
        at SafeSubscriber.next (webpack:///~/rxjs/Subscriber.js:174:0 <- src/test.ts:586:27) [ProxyZone]
        at Subscriber._next (webpack:///~/rxjs/Subscriber.js:125:0 <- src/test.ts:537:26) [ProxyZone]
        at Subscriber.next (webpack:///~/rxjs/Subscriber.js:89:0 <- src/test.ts:501:18) [ProxyZone]
        at CatchSubscriber.Subscriber._next (webpack:///~/rxjs/Subscriber.js:125:0 <- src/test.ts:537:26) [ProxyZone]
        at CatchSubscriber.Subscriber.next (webpack:///~/rxjs/Subscriber.js:89:0 <- src/test.ts:501:18) [ProxyZone]
        at MapSubscriber._next (webpack:///~/rxjs/operator/map.js:83:0 <- src/test.ts:13871:26) [ProxyZone]
Chrome 56.0.2924 (Mac OS X 10.10.5): Executed 9 of 9 (1 FAILED) (0.678 secs / 0.493 secs)

有什么想法吗?令人抓狂的是,我复制并粘贴了其他似乎工作得很好的服务的代码。我已经对这些文件进行了差异并且已经超过了它们一百万次,但是无法弄清楚为什么这个值不断变化。非常感谢任何帮助。

0 个答案:

没有答案