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.
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. 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.
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
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
. Just create a local variable
let kibanaDataServices;
beforeEach(() => {
kibanaDataServices = new KibanaDataServices()
});
And get rid of all your this
when referencing kibanaDataServices