Skip to content

dynamic imported React.lazy component using hooks throws 'Invalid hook call' #745

Closed
@li-yifei

Description

@li-yifei
  • @testing-library/react version: 10.4.6
  • Testing Framework and version: jest 26.1.0
  • DOM Environment: jest default jsdom

Relevant code or config:

# lazy-component.js
export default () => {
  const [value] = React.useState('I am lazy')
  return <div>{value}</div>
}
# test
const LazyComponent = React.lazy(() => import('../lazy-component'))
test('renders lazy', async () => {
  // this is how you test a component that needs a suspense component
  // just render it with your own suspense!
  render(
    <React.Suspense fallback="test loading">
      <LazyComponent />
    </React.Suspense>,
  )
  const lazyElement = await screen.findByText(/i am lazy/i)
  expect(lazyElement).toBeInTheDocument()
})

What you did:

Tried to render the whole with some lazy loaded components which using hooks.

What happened:

It throws

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

error when I call query methods from the render result or screen.

Reproduction:

There's a csb sample based on https://codesandbox.io/s/github/kentcdodds/react-testing-library-examples

https://codesandbox.io/s/throbbing-lake-op237?file=/src/lazy-component.js

Problem description:

Can't test high level componets including React.lazy children

Suggested solution:

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions