title: How to mock service function in Angular component for unit test
body: <p>I am writing unit test for angular app, I am testing if the service function  returns a value.</p>
  
  <p><strong>component.spec.ts</strong></p>
  
  <pre><code>import {TopToolBarService} from '../../top-toolbar/top-toolbar.service';
  
  beforeEach(async(() =&gt; {
     TestBed.configureTestingModule ({
     declarations: [ UsersListComponent],
     providers: [TopToolBarService],//tried mocking service here,still test failed
     schemas:[CUSTOM_ELEMENTS_SCHEMA]
   })
    .compileComponents();
  }));
  
  
  
  beforeEach(() =&gt; {
      fixture = TestBed.createComponent(UserListComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
    });
  
  
  
    it('should return data from service function', async(() =&gt; {
      let mockTopToolBarService: jasmine.SpyObj&lt;TopToolBarService&gt;;
      mockTopToolBarService = jasmine.createSpyObj('TopToolBarService', ['getCustomer']);
      mockTopToolBarService.getCustomer.and.returnValue("king");
      fixture.detectChanges();
      expect(component.bDefine).toBe(true); //fails
    }))
  
  </code></pre>
  
  <p><strong>component.ts</strong></p>
  
  <pre><code>bDefine = false;
  ngOnInit() {
   let customer = this.topToolBarService.getCustomer();
   if (customer == null) {
     bDefine = false;
   } else {
      bDefine = true;
     }
  }
  </code></pre>
  
  <p>I believe I have mocked the service function in my test, so I expect it must have reached else part where variable is set to 'true'.</p>
  
  <p><strong>TopToolBarService.ts</strong></p>
  
  <pre><code>import { EventEmitter, Injectable, Output } from "@angular/core";
  
  @Injectable()
  export class TopToolBarService {
  customer = null;
  
    getCustomer() {
      return this.customer;
    }
  }
  </code></pre>