Learner1
Learner1

Reputation: 109

Angular unit test for a method in a service which uses other services

I have a service in an angular application...inside that in a method I am having other couple of service calls in IF statement and returning values based on the result of service calls...sample code is below:-

//main service
getData(){
   if(this.serviceA.isReturnTrue() && this.serviceB.isEligible){
        return sample1;
   }
   if(this.serviceA.isReturnTrue() && !this.serviceB.isEligible && this.serviceB.isEligible != null){
        return sample2;
   }
   if(this.serviceA.isReturnTrue()){
      return c;
   }
   return d;
}

I need to write unit test for above method, I tried to use spyOn() for serviceA and serviceB but it did not worked...

Upvotes: 1

Views: 48

Answers (1)

Rの卄IT
Rの卄IT

Reputation: 677

You need to spyOn function to to mock the return value of serviceA.isReturnTrue() and 'serviceB.isEligible'.`

describe('MainService', () => { 
  let service: MainService; 
  let serviceA: ServiceA; 
  let serviceB: ServiceB; 
  
  beforeEach(() => { 
    TestBed.configureTestingModule({ 
      providers: [MainService, ServiceA, ServiceB] 
    }); 
    
    service = TestBed.inject(MainService); 
    serviceA = TestBed.inject(ServiceA); 
    serviceB = TestBed.inject(ServiceB); 
  }); 
    
    it('should return sample1 when serviceA.isReturnTrue() is true and serviceB.isEligible is true', () => { 
      spyOn(serviceA, 'isReturnTrue').and.returnValue(true); 
      spyOn(serviceB, 'isEligible').and.returnValue(true); 
      expect(service.getData()).toEqual('sample1'); 
    }); 
    
    it('should return sample2 when serviceA.isReturnTrue() is true and serviceB.isEligible is false and not null', () => { 
      spyOn(serviceA, 'isReturnTrue').and.returnValue(true); 
      spyOn(serviceB, 'isEligible').and.returnValue(false); 
      expect(service.getData()).toEqual('sample2'); 
    });

  })

If you need it I will share it Stackblitz Example. if needed

Upvotes: 0

Related Questions