ts-jest: jest.mock() makes module undefined when importing it no matter what we return in factory function
./src/StatelessComponent.tsx
import * as React from 'react';
import ChildComponent from './ChildComponent';
const StatelessComponent = () => (
<div>
<ChildComponent />
</div>
);
export default StatelessComponent;
./src/ChildComponent.tsx
import * as React from 'react';
const ChildComponent = () => (<b>Hello</b>);
export default ChildComponent;
./__tests__/StatelessComponent.test.tsx
jest.mock('../src/ChildComponent', () => 'ChildComponent');
// rest of the test here
When running the test in TS, ChildComponent is undefined.
When running the test in ES6, ChildComponent is defined.
Can be related to this issue in Jest repo: https://github.com/facebook/jest/issues/2984
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Reactions: 6
- Comments: 27 (3 by maintainers)
Ok I have a solution (actually my genius coworker @junseld found it).
It appears to have something to do with the way
import/exportbehaves in Typescript compared to ES6.Instead of this:
Do this:
I guess
default exportin ES6 allows the exported value to be imported directly, but Typescript creates a named export called “default”. So your mock needs to be an object with adefaultkey:{default: theDefaultExport}This is still an issue in 2022.
To mock an ES6 dependency module default export using jest:
Instead of:
What worked for me was:
The other options didn’t work for me.
Maybe we can update the ts-jest documentation to warn users about the differences in mocking compared to ES6?
I ask to reopen this issue due to lacking documentation / warnings of this issue.
The fact that
create-react-app-typescriptby default creates projects where mocking as documented doesn’t work is a big problem that had me stumbled for hours.That problem wouldn’t be as dire if
ts-jestdetected that a combination of typescript configs andjest.mockwith second parameter function that returns aundefinedand gave a proper warning/error message. This case might be whereimport ''in typescript never returns a undefined either way (not sure about dynamic import tho).Hey, I encounter similar issue. @adrifmonte when you do jest.mock(‘…/src/ChildComponent’); and ChildComponent.mockImplementation(() => ‘ChildComponent’); , does it show ts error saying that ‘mockImplementation does not exist on type ChildComponent’ . Please let me know
@dmngu9 be sure to NOT have
skipBabel: trueinglobals > ts-jestofjestconfiguration, elsejest.mockcalls won’t be hoisted. Also you can try addingesModuleInterop: trueto yourtsconfig.jsonif you have other issues like the original one of this thread.+1000
+1 in late 2023; running into this issue while trying to mock an RTK Query Api
@bhouser thanks.
The tests in the typescript directory of the linked repo pass if
"allowSyntheticDefaultImports": trueis added totsconfig.json+1000
I’ve just tried (within the repo with the changes I sent above):
as well as:
they both work