title: Unit test for a subscribe method in a component with Jasmine/Karma
body: <p>I want to test method with subscribe which invoked by ngOnInit in component. This method called getPagesJson, defined in getjsonService and gets one value from JSON file.</p>
  
  <p>Goal of the my test - put some value to the getPagesJson with a stub and will compare it with original data by testing process.</p>
  
  <p>The subscribe unit test doesn't work.
  Code below:</p>
  
  <p><strong>first-block.component.ts</strong></p>
  
  <pre class="lang-ts prettyprint-override"><code>import { Component, OnInit } from '@angular/core';
  import { GetJsonService } from '../../services/get-json.service';
  
  @Component({
    selector: 'app-first-block',
    template: '&lt;h1 class="page-title"&gt;{{h1}}&lt;/h1&gt;',
    styleUrls: ['./first-block.component.css']  
  })
  
  export class FirstBlockComponent implements OnInit {
  
    h1:any;
  
    constructor(private getjsonService: GetJsonService) { }
  
    ngOnInit() {
      this.getjsonService.getPagesJson()
      .subscribe(
        data =&gt; this.h1=data["index"][0]["h1"],
        error =&gt; console.log(error)
      );
    }
  }
  </code></pre>
  
  <p><strong>get-json.service.ts</strong></p>
  
  <pre class="lang-ts prettyprint-override"><code>import { Injectable } from '@angular/core';
  import { HttpClient } from '@angular/common/http';
  import { HttpErrorResponse } from '@angular/common/http';
  import { throwError } from 'rxjs';
  import { catchError, retry } from 'rxjs/operators';
  
  import { PagesInt } from '../interfaces/pages-int';
  
  @Injectable({
    providedIn: 'root'
  })
  export class GetJsonService {
  
      // Error handler
      private handleError(error: HttpErrorResponse) {
        if (error.error instanceof ErrorEvent) {
          console.error('Error message:', error.error.message);
        } else {  
          console.error(
            `Code from backend ${error.status}, ` +
            `Error: ${error.error}`);
        }
        return throwError(
          'Something is wrong');
      };
  
      constructor(private http: HttpClient) { }
  
      getPagesJson() {
        return this.http.get&lt;PagesInt&gt;('/assets/from-server/pages.json')
        .pipe( 
          retry(3), 
          catchError(this.handleError)
        );    
      }     
  }
  </code></pre>
  
  <p><strong>pages-int.ts</strong></p>
  
  <pre class="lang-ts prettyprint-override"><code>export interface PagesInt {
      h1:string;
      videoUrl?:string;
  }
  </code></pre>
  
  <p><strong>first-block.component.spec.ts</strong></p>
  
  <pre class="lang-ts prettyprint-override"><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
  import { of, Observable } from "rxjs";
  
  import { FirstBlockComponent } from './first-block.component';
  import { GetJsonService } from '../../services/get-json.service';
  
  describe('FirstBlockComponent', () =&gt; {
    let component: FirstBlockComponent;
    let fixture: ComponentFixture&lt;FirstBlockComponent&gt;;
    let spy: jasmine.Spy;
    let getjson: GetJsonService;
  
    const getJsonStub = {
      getPagesJson() {
        const data = [{h1: 'H1 with "Value"'}];
        return of( data );
      }
    };
  
    beforeEach(async(() =&gt; {
      TestBed.configureTestingModule({
        declarations: [ FirstBlockComponent ],
        providers: [ 
          { provide: GetJsonService, useValue: getJsonStub } 
        ]
      })
      .compileComponents();
      getjson = TestBed.get(GetJsonService);
    }));
  
    beforeEach(() =&gt; {
      fixture = TestBed.createComponent(FirstBlockComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
    });
  
    it('should create', () =&gt; {
      expect(component).toBeTruthy();
    });
  // Errors:
  // Uncaught TypeError: Cannot read property '0' of undefined thrown
  
  
    it('should called getPagesJson', async(() =&gt; {
      spy = spyOn(getjson, 'getPagesJson');
      fixture.detectChanges();
      fixture.whenStable().then(() =&gt; {
        expect(spy).toBeTruthy(); 
      });
    }));
  // Errors:
  // Failed: Cannot read property '0' of undefined
  
  
  // I'm using very simple and non asynchronous approach below
    it('should get H1 by getJsonService.getPagesJson()', () =&gt; {
      getjson.getPagesJson(); 
      fixture.detectChanges();
      expect(component.h1).toBe('H1 with "Value"');
    });
  // Errors:
  // Uncaught TypeError: Cannot read property '0' of undefined thrown
  // Expected undefined to be 'H1 with "Value"'.
  
  
  });
  </code></pre>