title: Angular Unit Test returns 'cannot read property of undefined' for Http Post
body: <p>I have a service where where my restpoints are being defined in the constructor so I've set up as variables. When I run my unit tests, these properties are returning as undefined. I'm relatively new to unit testing so I'm not sure if I missed an obvious step... </p>
  
  <p>Here's my service.ts:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
  import { Injectable } from '@angular/core';
  import { Router } from '@angular/router';
  import { Observable } from 'rxjs/Observable';
  
  @Injectable()
  export class PulldownService {
  
    public pulldownData: any = [];
    public restURL;
  
    constructor(public http: HttpClient, public router: Router) {
      this.getEnvConf().subscribe(
          res =&gt; {
            this.restURL = res[window.location.hostname];
          }
      );
    }
  
    getEnvConf(): Observable&lt;any&gt; {
      return this.http.get('./assets/data/environment-config.json');
    }
    postClaim() {
      let headerTarget;
      if (this.restURL['target_env']) {
        headerTarget = {'Accept': 'application/json', 'Content-Type': 'application/json', 'target_env': this.restURL['targetEnv']};
      } else {
        headerTarget = {'Accept': 'application/json', 'Content-Type': 'application/json'};
      }
      const httpHeaders = new HttpHeaders(headerTarget);
      const options = { headers: httpHeaders };
      return this.http.post( this.restURL['restEndPoint'],
        { 'names' : [
          'PersonRelationType',
          'State',
          ...
          ...
  
        ]}, options ).subscribe(
        data =&gt; {
          // Success!
          this.pulldownData.push(data);
        }
        ,
        (err: HttpErrorResponse) =&gt; {
          if (err.error instanceof Error) {
            // A client-side or network error occurred.
            this.router.navigateByUrl('/error');
            console.log('An error occurred:', err.error.message);
          } else {
            // The backend returned an unsuccessful response code.
            this.router.navigateByUrl('/error');
            console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
          }
        },
        () =&gt; {
          this.router.navigateByUrl('/getstart');
        }
      );
    }
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>Here's my service.spec.ts</p>
  
  <pre><code>import { PulldownService } from './pulldown.service';
  import { TestBed } from '@angular/core/testing';
  import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
  import { RouterTestingModule } from '@angular/router/testing';
  import { HttpRequest } from '@angular/common/http';
  
  describe('PulldownService', () =&gt; {
    let service: PulldownService;
    let httpTestingController: HttpTestingController;
  
    beforeEach(() =&gt; {
      TestBed.configureTestingModule({
        imports: [ HttpClientTestingModule, RouterTestingModule ],
        providers: [ PulldownService ]
      });
      httpTestingController = TestBed.get(HttpTestingController);
      service = TestBed.get(PulldownService);
    });
    describe('getEnvConfig', () =&gt; {
      it('should call get with the correct url', () =&gt; {
        // no subscribe method called in getEnvConfig
        // service.getEnvConf().subscribe();
        const req = httpTestingController.expectOne('./assets/data/environment-config.json');
        req.flush({ 'restEndPoint': 'http://localhost:8080/typelist?version=1', 'target_env': null});
        httpTestingController.verify();
        // expect(req.request.url.endsWith('environment-config.json')).toEqual(true);
      });
    });
    describe('postClaim', () =&gt; {
  
      it('should be called with proper arguments', () =&gt; {
        const responseForm = '&lt;form /&gt;';
        const pulldownService = TestBed.get(PulldownService);
        const http = TestBed.get(HttpTestingController);
        let postResponse;
  
        pulldownService.postClaim().subscribe((response) =&gt; {
          postResponse = response;
        });
        http.expectOne((request: HttpRequest&lt;any&gt;) =&gt; {
          return request.method === 'POST'
            &amp;&amp; request.url === 'http://localhost:8080/typelist?version=1'
            &amp;&amp; JSON.stringify(request.body) === JSON.stringify({
              names: ['State']
            })
            &amp;&amp; request.headers.get('Accept') === 'application/json'
            &amp;&amp; request.headers.get('Content-Type') === 'application/json'
            &amp;&amp; request.headers.get('target_env') === null;
        }).flush(responseForm);
        expect(postResponse).toEqual(responseForm);
      });
    });
  })
  </code></pre>
  
  <p>The error I keep getting is : TypeError: Cannot read property 'target_env' of undefined. Upon removing 'target_env' from my function, I see a new, different error for 'restEndPoint'. </p>
  
  <p>Any help on this would be greatly appreciated. Thanks</p>