question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Test fails because "Invalid hook call."

See original GitHub issue

💬 Questions and Help

Hello,

I’m facing an issue that I’m not able to solve with the following test:

import { screen } from '@testing-library/react';
import { getPage } from 'next-page-tester';

describe('Home page', () => {
  it('renders without crashing', async () => {
    const { render } = await getPage({
      route: '/',
      dotenvFile: '.env.local'
    });
    render();
    expect(screen.getByRole('heading', { name: 'HomePage' })).toBeInTheDocument();
  });

I got this error

Home page › renders without crashing

    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 https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

      22 |
      23 | export default function Popup(): JSX.Element {
    > 24 |   const [prefix, setPrefix] = useState<string>('');

with this component:

[...]

export default function Popup(): JSX.Element {
  const [prefix, setPrefix] = useState<string>('');
[...]

Do you know I can solve this?

Thank you,

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:23

github_iconTop GitHub Comments

3reactions
fracture91commented, Feb 16, 2021

I’m running into a similar issue with emotion/theme-ui. I have the jest patch installed. Here is a stack trace - not sure how useful it is. The offending hook call is here: https://github.com/emotion-js/emotion/blob/b59084b7cbfeab11c2a986033952d481d0b9fcf4/packages/react/src/context.js#L39

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 https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

      10 | class MyDocument extends Document {
      11 |   static async getInitialProps(ctx: DocumentContext) {
    > 12 |     const initialProps = await Document.getInitialProps(ctx)
         |                                         ^
      13 |     const styles = extractCritical(initialProps.html)
      14 | 
      15 |     return {

      at resolveDispatcher (node_modules/react/cjs/react.development.js:1476:13)
      at Object.useContext (node_modules/react/cjs/react.development.js:1484:20)
      at EmotionGlobal (node_modules/@emotion/react/dist/emotion-element-cb6e9ca7.cjs.dev.js:43:25)
      at processChild (node_modules/react-dom/cjs/react-dom-server.node.development.js:3353:14)
      at resolve (node_modules/react-dom/cjs/react-dom-server.node.development.js:3270:5)
      at ReactDOMServerRenderer.render (node_modules/react-dom/cjs/react-dom-server.node.development.js:3753:22)
      at ReactDOMServerRenderer.read (node_modules/react-dom/cjs/react-dom-server.node.development.js:3690:29)
      at Object.renderToString (node_modules/react-dom/cjs/react-dom-server.node.development.js:4298:27)
      at Object.renderPage (node_modules/next-page-tester/dist/_document/render.js:47:35)
      at Function.getInitialProps (node_modules/next/pages/_document.tsx:86:38)
      at getInitialProps (pages/_document.tsx:12:41)
      at node_modules/next-page-tester/dist/_document/fetchDocumentData.js:13:47
      at Object.executeAsIfOnServer (node_modules/next-page-tester/dist/server.js:29:22)
      at Object.fetchDocumentData [as default] (node_modules/next-page-tester/dist/_document/fetchDocumentData.js:13:21)
      at node_modules/next-page-tester/dist/_document/render.js:58:63
      at Object.executeAsIfOnServer (node_modules/next-page-tester/dist/server.js:29:22)
      at Object.serverRenderDocument (node_modules/next-page-tester/dist/_document/render.js:31:21)
      at getPage (node_modules/next-page-tester/dist/getPage.js:68:49)
      at Object.<anonymous> (__tests__/pages/blog/blog.tsx:17:26)

For some reason, I was able to get around the error on v0.19.0 by passing nonIsolatedModules: ["react"] in the getPage call. I have no idea why that works, since "react" is isolated by default by next-page-tester.

After that fix, I ran into trouble similar to #142 - it seemed like emotion was getting confused about whether it was running on the server or the client after I put its packages in nonIsolatedModules.

Luckily, v0.20.0 seems to have solved that problem (thank you!). But the nonIsolatedModules option was removed, reintroducing the “invalid hook call” error. I patched in something similar with patch-package and now my tests pass:

diff --git a/node_modules/next-page-tester/dist/utils.js b/node_modules/next-page-tester/dist/utils.js
index 59e916c..172ade2 100644
--- a/node_modules/next-page-tester/dist/utils.js
+++ b/node_modules/next-page-tester/dist/utils.js
@@ -80,6 +80,7 @@ exports.useMountedState = useMountedState;
 // @NOTE: This modules still need to preserve their identity between client and server
 // because we import them within our code which serves both environments :(
 const nonIsolatedModules = [
+    "react",
     'react',
     'next/dist/next-server/lib/head-manager-context',
     'next/dist/next-server/lib/router-context',

Again, I have no idea why that fixes it and this might introduce bugs of its own, but maybe this is helpful in the search for a long-term fix.

1reaction
toomuchdesigncommented, Feb 22, 2021

Hi @massimeddu-sonic, we’re working on a fix. We’ll release soonish in the upcoming days.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Test fails because "Invalid hook call." · Issue #147 - GitHub
Home page › renders without crashing Invalid hook call. Hooks can only be called inside of the body of a function component.
Read more >
Invalid hook call while testing with jest - react native
and error which I'm getting is: Invalid hook call. Hooks can only be called inside of the body of a function component.
Read more >
Invalid Hook Call Warning - React
There are three common reasons you might be seeing it: You might have mismatching versions of React and React DOM. You might be...
Read more >
Fix Invalid Hook Call Warning in React Tests - Sinistra
Damn. "Invariant Violation: Hooks can only be called inside the body of a function component." But... you ARE! Hope that helps!
Read more >
Solving React Hooks' invalid hook call warning - Rob Kendal
So what causes the invalid hook call warning? · You might have mismatching versions of React and React DOM. · You might be...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found