您好,我正在尝试按照以下过程为我的服务编写单元测试: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'))");
});
});
最佳答案
不要使用这个这个
.kibanaDataServices
。只需创建一个局部变量
let kibanaDataServices;
beforeEach(() => {
kibanaDataServices = new KibanaDataServices()
});
并在引用 kibanaDataServices
时删除所有 this
关于Angular2 测试服务——未定义的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39585745/