Swarup
Swarup

Reputation: 57

Not able to test if nested function is called in Jasmine

I'm learning to write test cases in jasmine ,I was trying to create a test case to check if the functions defined within the function are called

My function that I'm trying to test is as follows,and the sData method is written in another component that is being extended by current component

public rPage() {
    this.sData();
    this.setupPage()
  }

the test case that i wrote is as below

   it('should check if  sData is called', () => {
    const sData = spyOn<any>(component, 'sData');
    component.rPage();
    fixture.detectChanges();
    expect(sData).toHaveBeenCalled();
  });

have created spy on rpage already in beforeeach as below

 beforeEach(() => {
    fixture = TestBed.createComponent(BasicComponent);
    component = fixture.componentInstance;
    spyOn(component, 'rPage');
    fixture.detectChanges();
  });

still when i run the test ,the test case fails saying "Expected spy sData to have been called." ,where I'm going wrong

Upvotes: 0

Views: 1898

Answers (2)

PMO1948
PMO1948

Reputation: 2554

If you want to make sure that sData is called, you need to properly call rPage. By having spyOn(component, 'rPage'); in your beforeEach , you are effectively telling all your tests to never run rPage for real, and to just mock it. So therefore it is never called for real, an sData really will never be called.

In order for you to check rPage properly, you need to not use a spy in the test that tests it, or add .and.callThrough() to the spy to the function is actually called

Upvotes: 1

Owen Kelvin
Owen Kelvin

Reputation: 15083

You are calling the function then defining the spy, this is what is causing the problem. You need to define the spy then call the function.

Try below

  it('should check if sData is called', () => {
    const toggleSpy = spyOn<any>(component, 'sData');
    component.rPage();
    fixture.detectChanges();
    expect(toggleSpy).toHaveBeenCalled();
  });

Upvotes: 0

Related Questions