javascript - Mocka en standardexportfunktion med Jest: TypeError: (0 , _sampleFunction).default är inte en funktion
Jag har följande filer:
sampleFunction.ts:
export default (x: number) => x * 2;
testFil:
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();
});
När jag kör testFile.test.ts får jag följande fel:
TypeError: (0 , _sampleFunction).default is not a function
Hur kan jag mocka sampleFunction.ts med Jest när det har en standardexporterad funktion?
Svar #1
När man mockar en standardexport behöver man skicka både default och __esModule till jest:
const mockFn = jest.fn();
jest.mock("./sampleFunction", () => ({
__esModule: true,
default: mockFn,
}))
