angularrxjskarma-jasminespyon

spyOn response is coming back empty


it('should inject acaQQService and run getQQFormData', inject(
    [AcaQqService], (service: AcaQqService) => {
      const resp: QuickQuoteEntity  = <QuickQuoteEntity><unknown>[];
      spyOn(service, 'getQQFormData').and.returnValue(of(resp));
      expect(resp).not.toBeNull();
      console.log(resp);
    }));

When spying on this service call the data is coming back empty. The type conversion does not seem to be working for resp.


Solution

  • Please note that spyOn installs a spy onto a method of an existing object but it doesn't invoke that method. Therefore, between installing the spy on the method AcaQqService.getQQFormData and invoking expect, you need to call AcaQqService.getQQFormData.

    Also you don't check the result of AcaQqService.getQQFormData (an Observable) but the resp object defined inside the test. To make this work, it could be rewritten as follows.

    spyOn(service, 'getQQFormData').and.returnValue(of(resp));
    service.getQQFormData(...).subscribe(v => expect(v).toBe(resp));
    

    Such a test however wouldn't make sense because the tested method is mocked, hence no internals of the service are involved.