Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Jest spy not working while testing a function within a function

I’m trying to test a function in a class-based entity and trying to spy on another function that is being called inside the one I’m testing. But even though the child function is being called once, Jest fails to spy on it and says it was called 0 times.

Let’s say this is my class:

class Example {

  function1() {
    
    const data = this.function2();
    return data;

  }

  function2() {
    ...some code
  }

}

So to test function1, I’m doing this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

describe('ExampleComponent', () => {

  beforeEach(() => {
    client = new Example();
  });

  it('should call function2 once', async() => {
    const callFunction1 = client.function1();

    const function2Spy = jest.spyOn(client, 'function2');
    
    expect(function2Spy).toHaveBeenCalledTimes(1);
  });

});

What am I missing here?

>Solution :

You are calling function first then spying on another function.
Try spying before function call

describe('ExampleComponent', () => {

  beforeEach(() => {
    client = new Example();
  });

  it('should call function2 once', async() => {
 
    const function2Spy = jest.spyOn(client, 'function2'); 

    client.function1();
    
    expect(function2Spy).toHaveBeenCalledTimes(1);
  });

});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading