0

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:

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?

R. Richards
  • 24,603
  • 10
  • 64
  • 64
s.khan
  • 297
  • 1
  • 7
  • 24
  • 1
    Don't do this. Test doubles are for _collaborators_, not other parts of the thing you're supposed to be testing. Test the _behaviour_, through the public interface, and leave the internals as _implementation details_ you are then free to refactor as needed. – jonrsharpe Aug 10 '22 at 16:37
  • Yeah I will test function2 separately but testing function1, I want to check if it is called or not. – s.khan Aug 10 '22 at 16:52
  • 1
    Yes you should test `function2` separately (because it's also part of the public interface). No you should still not mock out `function2` when testing `function1`. Your boundary here is the class, **don't** tinker around inside it. (Worked example: https://stackoverflow.com/a/66752334/3001761.) – jonrsharpe Aug 10 '22 at 16:56
  • 1
    Whoa, that's actually makes sense. Amazing explanation. I never thought that way. Thank you so much. Learnt something new today. – s.khan Aug 10 '22 at 17:26

1 Answers1

1

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);
  });

});
Passionate Coder
  • 7,154
  • 2
  • 19
  • 44