Testing constructor condition

688 Views Asked by At

I am looking to get a 100% coverage and for it I am trying to test a condition inside a constructor of a component. So far I tryed to spy on the method during the component creation, mock the service and other approaches but nothig has worked. Any idea is welcome

export class Component {
    let enableAction: string;
    constructor(private readonly service:Service) {
        if(service.method()) {
           enableAction = "Action 1";
        } else {
           enableAction = "Action 2";
        }
    }
    ...
}
describe('component tests', () => {
   beforeEach(async ()=>{
      await TestBed.configureTestingModule({
           declarations: [Component],
           providers: [Service]
      }).compileComponents();
   });

   it('condition test', ()=> {
      const fixture = TestBed.createComponent(Component);
      const app = fixture.componentInstance;
      const service = TestBed.inject(Service);

      spyOn(service, 'method').and.ReturnValue(true);

      expect(app).toBeTruthy();
   });
})
1

There are 1 best solutions below

0
Jasdeep Singh On

You are not mocking the dependency before bootstrapping due to which you are not able to test the functionality inside the class. To incorporate this you should mock the dependency and this is the preferred way and definition of unit testing. Please do the changes as mentioned below and check if you are able to test it or not

describe('component tests', () => {
   let mockService;
   beforeEach(async ()=>{
      mockService = jasmine.createSpyObject('Service', ['method']);
      await TestBed.configureTestingModule({
           declarations: [Component],
           providers: [{provide: Service, useValue: mockService}]
      }).compileComponents();
   });

   it('condition test', ()=> {
      const fixture = TestBed.createComponent(Component);
      const app = fixture.componentInstance;
      const service = TestBed.inject(Service);

      spyOn(service, 'method').and.ReturnValue(true);

      expect(app).toBeTruthy();
   });
})

You can also return values from the mock service method like below:

mockService.method.and.returnValue(true)