title: What is the correct way to mock HttpClient and return an observable in angular unit testing?
body: <p>I have been working on this for an embarrassingly long period of time. I am trying to write a unit test for an angular app that mocks out HttpClient and returns an observable for the code being tested.</p>
  <p>My test looks like this</p>
  <pre><code>  beforeEach(async () =&gt; {
      await TestBed.configureTestingModule({
        declarations: [ ProjectComponent ],
        imports: [RouterTestingModule, HttpClientTestingModule],
        providers: [
          HttpClient
        ]
      })
      .compileComponents();
    });
  
    beforeEach(() =&gt; {
      fixture = TestBed.createComponent(ProjectComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
  
      var service = TestBed.get(HttpClient);
  
      var obs = Observable.create( observer =&gt; {
        observer.next({'hi':'hi'});
        observer.complete();
      });
      spyOn(service, 'get').and.returnValue(obs);
    });
  
    it('should create', () =&gt; {
      expect(component).toBeTruthy();
    });
  </code></pre>
  <p>My code to test looks like this.</p>
  <pre><code>  ngOnInit(): void {
      console.log('starting');
      const x = this.http.get('http://localhost:8080/project')
        x.subscribe((response: any) =&gt; {
          console.log('$$$$$$');
          console.log(response);
          this.projects = response;
        }, e =&gt; {
          console.log(e);
        });
    }
  </code></pre>
  <p>As you can see I want the observable to be returned by the get method as a mocked response. If i debug the variable x in the ngOninit method I see that the observable comes in there. But the subscribe function is never called. What is the matter with this? How can I get the subscribe function to be called? Am I creating/mocking the observable in the wrong way? ... Thanks in advance.</p>