2016-09-20 71 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