Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 514
Jimmy Avatar asked Oct 22 '25 11:10

Jimmy


1 Answers

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,
}))
like image 149
I'm Joe Too Avatar answered Oct 25 '25 01:10

I'm Joe Too