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?
-
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
, notTypeError: (0 , _sampleFunction).default is not a function
. – jonrsharpe Commented May 2, 2022 at 21:37
2 Answers
Reset to default 14When 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();
});