使用Jest模拟默认导出函数:类型错误:(0,_sampleFunction),默认值不是函数

mpgws1up  于 2022-12-08  发布在  Jest
关注(0)|答案(2)|浏览(167)

我有以下文件:

示例函数.ts:

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

测试文件:

import sampleFunction from './sampleFunction';

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

测试文件.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

sampleFunction.ts有一个默认的导出函数时,我如何用Jest模拟sampleFunction.ts

f5emj3cl

f5emj3cl1#

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

const mockFn = jest.fn();

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

6rqinv9w2#

我也遇到了同样的问题,我发现使用jest.spyOn对我很有效,我还必须传入一个mockImplementation来防止真实的的函数被调用。

import * as sampleFunction from './sampleFunction';
test('sample test', () => {
    const exportListSpy = jest.spyOn(sampleFunction, 'default').mockImplementation(() => undefined);
    testFile();
    expect(exportListSpy).toBeCalled();
});

相关问题