title: Angular2 testing service -- undefined service
body: <p>Hi I am trying to write unit tests for my service following this procedure: <a href="https://developers.livechatinc.com/blog/testing-angular-2-apps-dependency-injection-and-components/" rel="nofollow">https://developers.livechatinc.com/blog/testing-angular-2-apps-dependency-injection-and-components/</a> but I keep getting an error.</p>
  
  <p>Here is the service test</p>
  
  <pre><code>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', () =&gt; {
    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'))");
  });
  
  });
  </code></pre>
  
  <p>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.</p>
  
  <p>The error I get specifically is: </p>
  
  <pre><code> 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)
  </code></pre>
  
  <p>UPDATE:
  Not using "this" leads to an error of not defined in the "it" statement</p>
  
  <pre><code>describe('KibanaDataServices', () =&gt; {
  
    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'))");
    });
  
  });
  </code></pre>