Mocking a named export inside a table test calls the original function

50 viewsjavascriptjestjs
0

In Jest, I am attempting to mock a named export inside the body of a table test. However, when I run the test, the original implementation is being called instead of the mock.

I have reduced my situation to the following minimal implementation of the issue:

fileBeingTested.ts:

export function funcToBeTested() {
    return funcToBeMocked();
}

export function funcToBeMocked() {
    console.log('In actual');
    return false;
}

test.ts:

import * as fileBeingTested from './fileBeingTested';

describe('functionBeingTested', () => {
    afterAll(jest.restoreAllMocks);

    test.each([
        ['Result should be truthy', true],
        ['Result should be falsy', false],
    ])('%s, returns %s', (_, shouldResultBeTruthy) => {
        jest.spyOn(fileBeingTested, 'funcToBeMocked').mockImplementation(() => {
            console.log('In mock');
            return shouldResultBeTruthy;
        });

        const result = fileBeingTested.funcToBeTested();
        shouldResultBeTruthy ? expect(result).toBeTruthy() : expect(result).toBeFalsy();
    });
});

When I run the code I see:

In actual
In actual

I have also tried:

jest.spyOn(fileBeingTested, 'funcToBeMocked').mockReturnValue(shouldResultBeTruthy);

and:

jest.spyOn(fileBeingTested, 'funcToBeMocked').mockImplementation(
    jest.fn(() => {
        console.log('In mock');
        return shouldResultBeTruthy;
    })
);

However, I get the same result.

This is the documentation that I am attempting to follow.