Angular2 测试服务 -- 未定义服务

Angular2 testing service -- undefined service

您好,我正尝试按照以下过程为我的服务编写单元测试:https://developers.livechatinc.com/blog/testing-angular-2-apps-dependency-injection-and-components/ 但我一直收到错误。

这里是服务测试

import {it,inject,injectAsync,beforeEachProviders,TestComponentBuilder} from 'angular2/testing';
import {CORE_DIRECTIVES,FORM_DIRECTIVES,FormBuilder,ControlGroup,Validators,AbstractControl} from 'angular2/common';
import {KibanaDataServices} from "./kibana-data-services";
import {Http,Response,Headers, HTTP_PROVIDERS, ConnectionBackend} from 'angular2/http';
declare let $:JQueryStatic;

describe('KibanaDataServices', () => {
  beforeEach(function() {
  this.kibanaDataServices = new KibanaDataServices()

});


it("date properly formats for trends view",function(){
    // logs as {}
    console.log("this is " + JSON.stringify(this));
    // logs as undefined
    console.log("this.kibanaDataServices is " + this.kibanaDataServices);

    let dateQuery: string = this.kibanaDataServices.formulateQueryDates("7d");
    expect(dateQuery).toEqual("(from:'now-7d',mode:quick,to:'now'))");
});

});

而 console.log 是一个空对象,而 this.kibanaDataServices 只是未定义。我指定的路径是正确的,因为 kibana-data-services 和 kibana-data-services.spec.ts(这个测试文件)在同一个文件夹中,所以我不确定哪里出了问题。

我得到的具体错误是:

 TypeError: Attempted to assign to readonly property. in /Users/project/config/spec-bundle.js (line 42836)
TypeError: undefined is not an object (evaluating 'this.kibanaDataServices.formulateQueryDates') in /Users/project/config/spec-bundle.js (line 42841)

更新: 不使用"this"会导致在"it"语句

中未定义的错误
describe('KibanaDataServices', () => {

  beforeEach(function() {
  kibanaDataServices = new KibanaDataServices()

  });


  it("date properly formats for trends view",function(){
    console.log("kibanaDataServices is " + kibanaDataServices);

      let dateQuery: string = kibanaDataServices.formulateQueryDates("7d");
      expect(dateQuery).toEqual("(from:'now-7d',mode:quick,to:'now'))");
  });

});

不要使用这个 this.kibanaDataServices。只需创建一个局部变量

let kibanaDataServices;

beforeEach(() => {
  kibanaDataServices = new KibanaDataServices()
});

并在引用 kibanaDataServices

时删除所有 this