Weird `jest.mock` behaviour that forces code duplication
See original GitHub issueThis code works:
jest.mock('../../Spinner', () => () => <div>loading...</div>)
This code does not work:
const MockSpinner = () => <div>loading...</div>
jest.mock('../../Spinner', () => MockSpinner)
Error:
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Importing the mock spinner component from another file also fails with error:
import Spinner from '__mocks__/Spinner'
jest.mock('../../Spinner', () => Spinner)
Error:
babel-plugin-jest-hoist: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables.
How can I prevent code duplication when mocking jest components? 😦
Issue Analytics
- State:
- Created 5 years ago
- Reactions:4
- Comments:6
Top Results From Across the Web
Jest: avoiding manual mock code duplication - Stack Overflow
I have the module mocked in one of my repos, by creating a manual mock in the mocks directory, and that works fine....
Read more >The only 3 steps you need to mock an API call in Jest
The unmocked code. We're going to be testing this getFirstAlbumTitle() function, which fetches an array of albums from an API and returns the ......
Read more >Integrated Tests Are A Scam - The Code Whisperer
If you test mostly through integrated tests, then you'd have to write the same tests over and over again for every date field,...
Read more >Effective Python Testing With Pytest
This requires duplicating test code, and doing so can sometimes obscure the behavior that you're trying to test.
Read more >The last guide to the useEffect Hook you'll ever need
For example, the official React docs show that you can avoid the duplicated code that results from lifecycle methods with one useEffect ...
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 Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I also tried
__mocks__
folder:Then in my test file:
Results in error:
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.