1

I have a service service1. I want to test the method getDetails() of this. This method uses another service service2 to make an HTTP call using getData() method and returns a promise. The function is as below:

service1 {

   constructor(
       private service2 : Service2,
       private service3 : Service3
   ){}
   
   getDetails(id: string): any{
       let url = Utilty.format(id);
       return service2.getData(url).pipe(map(this.service3.setData)).toPromise();
   }
}

The code that I have written for testing is as below:


describe('service1', () => {
    let service1: Service1;

    let service2Spy: Jasmine.spyObj(Service2);
    beforeEach(() => {
        TestBed.configureTestingModule({
            imports:  [HttpClientModule, HttpClientTestingModule],
            providers: [HttpClient,
            {provide: Service2, useValue: jasmine.createSpyObj('Service2', ['getData'])}
            ]
        });
        service1: TestBed.get(Service1);
        service2Spy: TestBed.get(Service2);
    })

    it('check if getData returns correct response', function done() {
        // in respnse I have taken a constant json that is expected
        service2Spy.getData.and.returnValue(Promise.resolve(of(response)));
        service1.getDetails('abc').then((result)=> {
            expect(service2Spy.getData).toHaveBeenCalled();
            done();
        })

    })
})

I want to test whether the below scenarios:

  1. Is getData() is called or not?
  2. What are the parameters with which getData is called?
  3. Are we getting the correct response from getDetails?

But I keep getting this error:

cannot read properties of undefined (reading 'pipe')
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
user16806836
  • 91
  • 1
  • 1
  • 3
  • The absolute minimum requirement for a test double is that it matches the interface of the thing that it's supposed to be replacing. Your code (presumably, although not necessarily, correctly) expects the method to return an observable, and the test double returns a _promise_ of an observable. – jonrsharpe Jun 14 '22 at 14:41
  • Please use your actual code for this situation because your code have lots of typos that would have been thrown aside from the error you pointed out. – Get Off My Lawn Jun 14 '22 at 14:53

0 Answers0