'Mocking a default export function with Jest: TypeError: (0 , _sampleFunction).default is not a function

I have the following files:

sampleFunction.ts:

export default (x: number) => x * 2;

testFile:

import sampleFunction from './sampleFunction';

export default () => {
  const n = sampleFunction(12);
  return n - 4;
};

testFile.test.ts:

import testFile from './testFile';

const mockFn = jest.fn();

jest.mock('./sampleFunction', () => ({
  __esModule: true,
  default: mockFn,
}));

test('sample test', () => {
  testFile();
  expect(mockFn).toBeCalled();
});

When I run testFile.test.ts, I get the following error:

TypeError: (0 , _sampleFunction).default is not a function

How can I mock sampleFunction.ts with Jest when it has a default exported function?



Solution 1:[1]

When mocking a default export, you need to pass both default and __esModule to jest:

const mockFn = jest.fn();

jest.mock("./sampleFunction", () => ({
  __esModule: true,
  default: mockFn,
}))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 I'm Joe Too