[英]Angular2 testing service -- undefined service
Hi I am trying to write unit tests for my service following this procedure: https://developers.livechatinc.com/blog/testing-angular-2-apps-dependency-injection-and-components/ but I keep getting an error.嗨,我正在尝试按照以下过程为我的服务编写单元测试: https : //developers.livechatinc.com/blog/testing-angular-2-apps-dependency-injection-and-components/,但我一直收到错误消息。
Here is the service test这是服务测试
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'))");
});
});
And the console.log for this is an empty object, and this.kibanaDataServices is simply undefined.而这个 console.log 是一个空对象,而 this.kibanaDataServices 只是未定义。 The path I am specifying is correct as kibana-data-services and kibana-data-services.spec.ts (this test file) are in the same folder so I am not sure what is wrong.
我指定的路径是正确的,因为 kibana-data-services 和 kibana-data-services.spec.ts(这个测试文件)在同一个文件夹中,所以我不确定出了什么问题。
The error I get specifically is:我具体得到的错误是:
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: Not using "this" leads to an error of not defined in the "it" statement更新:不使用“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'))");
});
});
Don't use this this
.kibanaDataServices
.不要使用
this
.kibanaDataServices
。 Just create a local variable只需创建一个局部变量
let kibanaDataServices;
beforeEach(() => {
kibanaDataServices = new KibanaDataServices()
});
And get rid of all your this
when referencing kibanaDataServices
并在引用
kibanaDataServices
时摆脱所有this
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.