mahmoud chebbani
mahmoud chebbani

Reputation: 75

How to override a function inside ngOnInit in jasmine when creating an angular component in TestBed?

I have an ngOnInit function that is calling another function inside the same component and I'm testing this component using jasmine test.

I would like to mock the function that is inside the ngOnInit function to prevent the original implementation from executing.

  ngOnInit(): void {
    this.initializeData();
  }

I tried the following implementation in my before each function but this way ngOninit will execute twice:

  beforeEach(() => {
    testHostFixture = TestBed.createComponent(TestHostComponent);
    testHostComponent = testHostFixture.componentInstance;
    spyOn(testHostComponent, 'initializeData').and.callFake(()=>{console.log("replacement");});
    testHostComponent.ngOnInit();
    testHostFixture.detectChanges();
  });

Is there anyway to mock the implementation of the function 'initializeData' before ngOnInit executes for the first time ?

Thanks.

Upvotes: 1

Views: 3178

Answers (1)

James
James

Reputation: 2895

You need to spy before you create the component. So just move the spy above the creation line.

  beforeEach(() => {
    spyOn(testHostComponent, 'initializeData').and.callFake(()=> 
    {console.log("replacement");});
    testHostFixture = TestBed.createComponent(TestHostComponent);
    testHostComponent = testHostFixture.componentInstance;

    testHostComponent.ngOnInit();
    testHostFixture.detectChanges();
  });

Your ngOnInit() will have been called twice here as the component runs ngOnInit() when it is created in the TestBed. If you only want it to be called once. Remove the explicit call testHostComponent.ngOnInit();

Upvotes: 3

Related Questions