2016-09-20 61 views
1

嗨我试图为我的服务编写单元测试遵循此过程:https://developers.livechatinc.com/blog/testing-angular-2-apps-dependency-injection-and-components/但我不断收到错误。Angular2测试服务 - undefined服务

这里是服务测试

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) 

UPDATE: 不使用“这个”导致了“它”语句定义的不是一个错误

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

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

let kibanaDataServices; 

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

,摆脱所有的引用kibanaDataServices

+0

当,但我怎么能在beforeEach定义,并访问它的“它”的语句this。我无法创建一个全球性的,因为我处于严格模式 – es3735746

+0

这不是全球性的。尝试一下。在我之前发布的'beforeEach' –

+0

之前声明吧。 – es3735746