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

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

我有以下文件:

sampleFunction.ts:

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

测试文件:

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();
});

当我 运行 testFile.test.ts 时,出现以下错误:

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

当 Jest 具有默认导出函数时,我如何模拟 sampleFunction.ts

模拟默认导出时,您需要将 default__esModule 都传递给 jest:

const mockFn = jest.fn();

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