title: How to test success and error cases of an observable subscription
body: <p>My goal is to unit test success and error cases of the function <code>getData()</code>. In success case, <code>this.success</code> function must have been called. In error case, <code>this.failure</code> function must have been called. </p>
  
  <pre><code>export class MyComponent implements OnInit {
  
    constructor() {}
  
    ngOnInit() {
      this.getData();
    }
  
    getData(): void {
    this.myService.getServiceData().subscribe( 
       //returns an observable
      (result) =&gt; {
        this.success(result);
      },
      error =&gt; {
        this.failure(error);
      }
    );
    }
  }
  </code></pre>
  
  <p>This is my unit test:</p>
  
  <pre><code>describe('MyComponent', () =&gt; {
    let component = MyComponent;
    let fixture: ComponentFixture&lt;MyComponent&gt;;
    let myService = jasmine.SpyObj&lt;MyServiceClass&gt;;
  
    beforeEach(async(()=&gt; {
      myService = jasmine.createSpyObj('MyServiceClass', ['getServiceData']);
  
      TestBed.configureTestingModule({
        providers: [
          { provide: MyServiceClass, useValue: myService }
        ]
      }).compileComponents();
  
      fixture = TestBed.createComponent(MyComponent);
      component = fixture.componentInstance;
  
    }));
  
    it('should call success function', async(() =&gt; {
      spyOn(component, 'success');
      myService.getServiceData.and.returnValue(asyncData(myMockObj));
      component.getData();
      //fails. If I expect failure() to be called, it ALSO fails!
      expect(component.success).toHaveBeenCalled();
    }));
  })
  </code></pre>
  
  <p>asyncData function looks like that:</p>
  
  <pre><code>export function asyncData&lt;T&gt;(data: T) {
    return defer(() =&gt; Promise.resolve(data));
  }
  </code></pre>
  
  <p>Why is it failing and how can I test those two cases?</p>