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?
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,
}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With