0

I am using Angular with Jest to mock a class. I am finding difficulty in mocking the constructor as the test function is invoked within the constructor. Any input on how to mock the constructor with jest would be helpful

export class AppComponent {


constructor(){

this.test();

}

test(){

return 'Test'
}
}

test

describe( 'AppComponent', () => {
    let fixture: WorkerFormComponent;

    beforeEach( () => {
        
        fixture = new AppComponent(
            
        );
    });
R. Richards
  • 24,603
  • 10
  • 64
  • 64
Subham
  • 420
  • 3
  • 11
  • 34
  • Please, explain your case. Mocking a constructor doesn't make sense in JS because `constructor` is a class itself. What are you're trying to do and why? Do you want to mock AppComponent in its own test? *I am finding difficulty in mocking the constructor as the test function is invoked within the constructor* - why is this a problem? – Estus Flask May 05 '21 at 03:14

1 Answers1

0

Why not try to just mock the method inside the constructor, rather than the whole constructor itself?

describe('AppComponent', () => {
  let component: WorkerFormComponent;
  let fixture: ComponentFixture<WorkerFormComponent>;

  beforeEach(() => {
    fixture = TestBed.createComponent(WorkerFormComponent);
    component = fixture.componentInstance;
  });

  it('should mock and call the test function', () => {
    const testFnSpy = jest.spyOn(component, 'test')
                          .mockImplementation(() => 'Mock Value Returned');
    component.fireMethod(); // some method unrelated to the constructor
    expect(testFnSpy).toHaveBeenCalled();
  });
});

This solution uses a spy, if you wish to remove the mockImplementation, you can do so.

Derrick Rose
  • 664
  • 2
  • 9
  • 21