title: Angular unit-testing spyOn service from component
body: <p>I've got a login component and I want to test it whether it calls the service's method with proper values, however I don't know how to spy on that service from the component.</p>
  
  <p>I've tried</p>
  
  <pre><code>beforeEach(() =&gt; {
  ...
  authService = TestBed.get(AuthService);
  });
  </code></pre>
  
  <p>And this is not working</p>
  
  <pre><code>it('should pass proper values', () =&gt; {
      const submitSpy = spyOn(authService, 'signInByLogin');
      const loginSpy = spyOn(component, 'signIn').and.callThrough();
  
      const username = fixture.debugElement.query(By.css('#username'));
      const password = fixture.debugElement.query(By.css('#password'));
      const submitBtn = fixture.debugElement.query(By.css('[type="submit"]'));
  
      username.nativeElement.value = 'test';
      password.nativeElement.value = 'password';
  
      fixture.detectChanges();
  
      expect(username.nativeElement.value).toBe('test');
      expect(password.nativeElement.value).toBe('password');
      expect(submitBtn).toBeTruthy();
  
      fixture.detectChanges();
  
      submitBtn.triggerEventHandler('click', null);
  
      fixture.whenStable().then(() =&gt; {
          expect(loginSpy).toHaveBeenCalled();
          expect(submitSpy).toHaveBeenCalledWith('test', 'password');
      });
  });
  </code></pre>
  
  <p>It says</p>
  
  <blockquote>
    <p>An error was thrown in afterAll
    Expected spy signInByLogin to have been called with [ 'test', 'password' ] but actual calls were [ '', '' ].</p>
  </blockquote>
  
  <p>The service's method is called from the private function in login component.
  And the call is</p>
  
  <pre><code>this.authService
              .signInByLogin(this.form.controls['login'].value, this.form.controls['password'].value).subscribe(...)
  </code></pre>