简体   繁体   中英

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:

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?

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

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM