I have a Gatsby site alongside a components library. When running the Gatsby site, I was getting an "Invalid hook call" error, and adding a Webpack alias like suggested here solved the issue.
Now, I'm getting a similar "Invalid hook call" error when running tests using Jest and react-testing-library:
Error: Uncaught [Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See ... for tips about how to debug and fix this problem.]
at reportException (/Users/misha/temp/invalid-hook-repro/basis/node_modules/jsdom/lib/jsdom/living/helpers/runtime-script-errors.js:62:24)
at innerInvokeEventListeners (/Users/misha/temp/invalid-hook-repro/basis/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:333:9)
at invokeEventListeners (/Users/misha/temp/invalid-hook-repro/basis/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:274:3)
at HTMLUnknownElementImpl._dispatch (/Users/misha/temp/invalid-hook-repro/basis/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:221:9)
at HTMLUnknownElementImpl.dispatchEvent (/Users/misha/temp/invalid-hook-repro/basis/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:94:17)
at HTMLUnknownElement.dispatchEvent (/Users/misha/temp/invalid-hook-repro/basis/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:231:34)
at Object.invokeGuardedCallbackDev (/Users/misha/temp/invalid-hook-repro/basis/node_modules/react-dom/cjs/react-dom.development.js:237:16)
at invokeGuardedCallback (/Users/misha/temp/invalid-hook-repro/basis/node_modules/react-dom/cjs/react-dom.development.js:292:31)
at beginWork$1 (/Users/misha/temp/invalid-hook-repro/basis/node_modules/react-dom/cjs/react-dom.development.js:23203:7)
at performUnitOfWork (/Users/misha/temp/invalid-hook-repro/basis/node_modules/react-dom/cjs/react-dom.development.js:22157:12)
I tried to check for multiple versions of React:
$ npm ls react
└── react@16.13.1
$ npm ls react-dom
└── react-dom@16.13.1
And, also tried to alias react in jest.config.js:
moduleNameMapper: {
react: "<rootDir>/website/node_modules/react",
...
}
But, this results in:
TypeError: React.createContext is not a function
Any ideas?
To reproduce the issue:
1. git clone https://github.com/moroshko/basis.git
2. cd basis
3. git checkout 52f1dc7
4. npm install
5. ./node_modules/.bin/cross-env BABEL_ENV=cjs ./node_modules/.bin/jest -- -t Playground