0

I'm trying to test a class that makes HTTP calls, mocking out the calls. I haven't actually set up my mock HTTP call yet so I would expect the test to fail, but it passes. How do I get the test to fail if the Observable doesn't return anything?

Here's my test:

describe('my service', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpModule],
      providers: [
        MyService,
        { provide: XHRBackend, useClass: MockBackend }
      ]
    });
  });

  it('should return a Candidate', async(inject([MyService], (service: MySerivce) => {
    // given
    const candidateId = 'test@test.com';

    // when
    service.getCandidate(candidateId).subscribe(candidate => {
        expect(candidate.Id).toBe(candidateId);
        // will have some other assertions here
    });
  })));
});

The MyService.getCandidate method does something like this:

public getCandidate(candidateId: string): Observable<Candidate> {
  const url = '<my url>';
  return this.http.get(url)
    .map(this.parseCandidate);
}
Kai G
  • 3,371
  • 3
  • 26
  • 30
  • Never write test cases which subscribes to Observables. you need to hard code the data and mock the test case and not the actual implementation – Aravind Apr 05 '17 at 04:11
  • @Aravind then how do you suggest I test a method that returns an Observable? – Kai G Apr 05 '17 at 04:28
  • Have a look at this [**answer**](http://stackoverflow.com/questions/42557567/angular2-http-call-unit-testing/42603249#42603249) – Aravind Apr 05 '17 at 04:30
  • 1
    I don't really see how that answer would help me here. I'm trying to test what the method returns, not the internals of my service. I've just figured out how to solve the problem, will post my answer shortly. – Kai G Apr 05 '17 at 04:38
  • You have not really provided MockMyService for MyService. So the actual MyService method is getting called. You can create MockMyService and write getCandidate() method in it to return fake data. – Amit Chigadani Apr 05 '17 at 04:55
  • Yes that's exactly what I want to do. I'm testing MyService so I want to mock out the HTTP call only. – Kai G Apr 05 '17 at 05:07
  • @KaiG any chance you could share that solution? – user2836501 Apr 26 '18 at 22:18
  • @user2836501 Sorry I must have to got distracted at the time. I've since upgraded the project to Angular 5 so using HttpClientModule rather than HttpModule now. – Kai G Apr 26 '18 at 23:16

0 Answers0