最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited May 2, 2022 at 21:35 jonrsharpe 122k30 gold badges267 silver badges474 bronze badges asked May 2, 2022 at 17:59 JimmyJimmy 3,87016 gold badges50 silver badges111 bronze badges 2
  • 1 => ({ default: mockFn })? – jonrsharpe Commented May 2, 2022 at 19:42
  • 2 With your latest version (and various assumptions around setup it'd be nice if we didn't have to make) I get ReferenceError: Cannot access 'mockFn' before initialization, not TypeError: (0 , _sampleFunction).default is not a function. – jonrsharpe Commented May 2, 2022 at 21:37
Add a ment  | 

2 Answers 2

Reset to default 14

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,
}))

I ran into the same issue. I found that using jest.spyOn worked for me. I also had to pass in a mockImplemention to prevent the real function from being called.

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论