Search code examples
angularkarma-jasmineangular2-servicesangular-test

Cannot read property 'subscribe' of undefined karma jasmine


I need to create a test of this get, but every time I try I get the error "TypeError: Cannot read property 'subscribe' of undefined"

My service function

getAPICard(): Observable<any> {
return this.http.get<any[]>(`${this.GET_APICard}`);

}

My spec.ts

it('testing get api', (done:DoneFn) =>{
  const mockObj = [{id:'1',
   title:'title', 
   description:'description',
   image: 'imagem',
   amount: 10
  }];

  httpClientSpy.get.and.returnValue(of(mockObj)).and.callThrough();

 modalIndicationService.getAPICard().subscribe(
   dados => {
    expect(dados).toEqual(mockObj, 'mockObj');
    done()
   },
   done.fail
 )
  
  expect(httpClientSpy.get.calls.count()).toBe(1, 'one call');
  done();

})


Solution

  • I think you can't have both .and.returnValue and .and.callThrough(). Only one of the two makes sense because returnValue will always return a value and callThrough will call the actual function.

    Try changing this line to:

    httpClientSpy.get.and.returnValue(of(mockObj));
    

    The rest looks good.