angularkarma-jasmineangular-testspyon

Unable to do angular unit testing due to method call present inside constructor


Unable to run angular unit test due to method present inside component constructor.

 export class AppComponent  {
  name = 'Angular 4';
   constructor(){
    this.testMethod();
   }

   testMethod(){
         console.log("test method");
   }

  testMethodNonc(){
     console.log("test method nc");
  }
}

//my spec file

describe('MyComponent', () => {
  let fixture, element;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent  
      ]
    });

    fixture = TestBed.createComponent(AppComponent);
    element = fixture.debugElement;
  })
  it('works', () => {
    fixture.detectChanges();
    expect(component.testMethodNonc()).toHaveBeenCalled();
  });
});

when i tried to run unit test for testMethodNonc() ,function testMethod() also running along with this method since its present inside constructor. is it possible to execute testMethodNonc() alone by mocking function testMethod?


Solution

  • Since you're creating a new instance of the class, it'll keep calling testMethod. You can spy on testMethod and callFake instead of calling the method. You could also use a beforeAll instead of a beforeEach so the component is only created once for the test. This way, the method will only be called initially when the component is created.

    After your component is created, you can call any method you like and test them individually.