title: Angular Unit Test - Cannot read properties of undefined (reading 'subscribe')
body: <p>I am using Angular / Jasmine for unit tests.<br />
  Currently I am testing a component with an Input field + &quot;Add&quot; button.<br />
  &quot;Add&quot; should call a add() function with a service behind it.</p>
  <p>I want to test if the service method was called.</p>
  <p>I have two test for this.<br />
  One is working, (Add value to Input field &amp; click the &quot;Add&quot; Button)<br />
  One is not working. (calling the add() method directly behind the &quot;Add&quot; Button)\</p>
  <p>The error <strong>ERROR: TypeError: Cannot read properties of undefined (reading 'subscribe')</strong> indicates that the service is undefined. But I don't understand why the service is in one testcase defined and in the other not?</p>
  <p>Here is a Stackblitz with Jasmine-Test : <a href="https://stackblitz.com/edit/angular-ivy-dnzv96?file=src/app/app.component.spec.ts" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-ivy-dnzv96?file=src/app/app.component.spec.ts</a></p>
  <p><strong>HTML</strong></p>
  <pre><code>&lt;div&gt;
    &lt;label&gt;Hero name:
      &lt;input #heroName /&gt;
    &lt;/label&gt;
    
    &lt;button (click)=&quot;add(heroName.value)&quot;&gt;
      add
    &lt;/button&gt;
  &lt;/div&gt;
  </code></pre>
  <p><strong>The add() method</strong></p>
  <pre><code> add(name: string): void {
      this.heroService.addHero({ name })
        .subscribe(hero =&gt; {
          this.heroes.push(hero);
        });
    }
  </code></pre>
  <p><strong>The two Test</strong></p>
  <pre><code>  describe('should call HeroService.addHero()',() =&gt; {
  
      **// WORKING TEST**
      it('by using input dialog and click &quot;Add&quot; button', () =&gt; {
        const input = el.query(By.css('input')).nativeElement;
        input.value = 'NewHero';
        const button = el.query(By.css('button'));
        button.triggerEventHandler('click', null)
        fixture.detectChanges;
  
        expect(mockHeroService.addHero).toHaveBeenCalledWith({ name: 'NewHero' } );
      })
  
      **// FAILING TEST - ERROR: TypeError: Cannot read properties of undefined (reading 'subscribe')**
      it('by calling method add()', (() =&gt; {
        component.add('newHero');
  
        expect(mockHeroService.addHero).toHaveBeenCalledWith({ name: 'NewHero'} );
      }))
    })
  </code></pre>