1

I am new to unit testing and I have a component in my project which in its constructor a method is being called

export class myComponent {
constructor(){       
        this.someMethod();
   }

public someMethod(){
 //some code
}

I want to test if the method is being called with this test suite:

it('should call for the someMethod', () => {
    spyOn(component, 'someMethod')   //also tried .and.callThrough();

    expect(component.someMethod).toHaveBeenCalled();;
});

The problem is while with my debugging I can make sure the method is being called, the test will always fail.

would really appreciate it, if someone help.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
n.sh
  • 347
  • 4
  • 19

1 Answers1

4

As explained in this answer, one of the benefits of using prototype methods is that they can be spied or mocked before class instantiation. Considering that this is TypeScript code that has controller class exported, it is:

it('should call for the someMethod', () => {
    spyOn(ComponentClass.prototype, 'someMethod');
    // instantiate ComponentClass class
    expect(component.someMethod).toHaveBeenCalled();
});

It is generally a bad habit to make a constructor contain initialization logic, particularly because this makes classes harder to test and extend. Since AngularJS already offers controller hooks, it is desirable to move all intialization logic to $onInit, unless there are lifecycle-related timing problems.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565