jest.mock() makes module undefined when importing it no matter what we return in factory function
See original GitHub issue./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
Issue Analytics
- State:
- Created 7 years ago
- Reactions:6
- Comments:26 (3 by maintainers)
Top Results From Across the Web
jest.fn() inside jest.mock() returns undefined - Stack Overflow
I know there is different ways to mock a module but I'm curious to understand the issue that I'm facing. any idea what...
Read more >How to mock imported functions with Jest - DEV Community
We 'll start by testing the case of isInteger() returning false . The isInteger.js module has a single default export - the isInteger()...
Read more >Mock Functions - Jest
You can create a mock function with jest.fn() . If no implementation is given, the mock function will return undefined when invoked.
Read more >MockBuilder - the simplest way to create mocks in Angular tests
Do not forget to return the promise of MockBuilder. ... It will mock and import TargetModule in TestBed ... getP1() returns undefined
Read more >Jest Full and Partial Mock/Spy of CommonJS and ES6 Module ...
mock ) is a factory for the module. ie. it's a function that returns a mock module object. Second, if you want to...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Ok I have a solution (actually my genius coworker @junseld found it).
It appears to have something to do with the way
import
/export
behaves in Typescript compared to ES6.Instead of this:
Do this:
I guess
default export
in 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 adefault
key:{default: theDefaultExport}
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.