Jest – mock a function being called from the function under test

  javascript, jestjs, mocking, node.js, unit-testing

I have a utils.js file with a function that calls another function in the same file. Like this:

// utils.js    
async function originalFunc (params) {

    await anotherFunc(arg1, arg2)

In another file I’m using jest to test the originalFunc

// utils.test.js
test('should test orginalFunc', async () => {
    const params = {
        arg1: 'data1',
        arg2: 'data2',

    const anotherFunc = jest.fn()

    await util.originalFunc(params)

    // todo: expect anotherFunc to be called with correct params

However when using this configuration the real anotherFunc is being called rather than the mock jest.fn() version.

I’ve also tried mocking the module like this:

jest.mock('../src/util', () => ({
    anotherFunc: jest.fn(),

But that does not work either.

How can I force originalFunc to use a mocked implementation of anotherFunc?

Source: Ask Javascript Questions