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

时间:2016-09-20 04:34:15

标签: angular karma-jasmine karma-mocha angular2-testing

您好我正在尝试按照以下步骤为我的服务编写单元测试: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)

更新: 不使用"这个"导致错误未被定义在"它"声明

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'))");
  });

});

1 个答案:

答案 0 :(得分:1)

请勿使用此 this .kibanaDataServices。只需创建一个局部变量

let kibanaDataServices;

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

在引用this

时摆脱所有kibanaDataServices