Jestjs how to test function being called inside another function

not sure if this will help but it may give you ideas.

first, the example above:

// this needs to be stubbed
// const childFunction = () => 'something';
const childFunction = jest.fn();

const parentFunction = () => childFunction();

it('childFunction should be called', () => {
    parentFunction();
    expect(childFunction).toHaveBeenCalled();
}

this is a somewhat contrived example as it's unlikely that childFunction is exported so you cannot get a reference to it and mock/stub it.

one workaround you have would be to move it out into its own method

class Component extends React.Component {
  componentDidMount() {
    this.parentFunction();
  }
  parentFunction() {
    parentFunction(); // from elsewhere
  }
  render() {...}
}

This allows you to create a puncture and spy on the Component proto.

eg

const spy = jest.spyOn(Component.prototype, 'parentFunction');

// ... mount so lifecycle runs... 
expect(spy).toHaveBeenCalled(); // and clear the spy mocks after!

it may be better to mock the module

eg you have utils.js used by your component that does:

export function parentFunction(){ console.log('parent'); }

component.js does:

import { parentFunction } from './utils';

you could in your tests do:

const utils = require('./utils');
utils.parentFunction = jest.fn();
import Component from './component';
// later
expect(utils.parentFunction).toHaveBeenCalled();

as you can see, many possible ways to go, though I am not sure on the value of that test, you should probably test the output / functionality of the component rather than it had called, having something run on componentDidMount is a given and would only break if somebody converted to functional or changed the lifecycle name.


There's no way to spy on function call if a function isn't called as object method.

As explained in this answer, due to how ES modules work, it's possible to spy or mock a function only if it was exported from a module and is used in another module. This way it can be spied on module * object, or be mocked with jest.mock.

If this isn't the case, it should be tested indirectly:

expect(childFunction()).toBe('something');
expect(parentFunction()).toBe('something');