react: Cannot shallow render a component containing hooks

Do you want to request a feature or report a bug? A bug

What is the current behavior? An error is thrown: Invariant Violation: Hooks can only be called inside the body of a function component.

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem. Your bug will get fixed much faster if we can run your code and it doesn’t have dependencies other than React. Paste the link to your JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new) example below: App.js

import React, { useState } from 'react'

const App = () => {
  const [name, setName] = useState('Chris')
  return (
    <div>Hello { name }</div>
  )
}

export default App

Test.js

import React from 'react'
import ShallowRenderer from 'react-test-renderer/shallow'
import App from './components/App'

const renderer = new ShallowRenderer()
renderer.render(<App />)

What is the expected behavior? We should be able to shallow render a component with hooks like any other component (Enzyme too)

Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React? 16.7.0-alpha.0

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 21
  • Comments: 16

Most upvoted comments

It’s definitely a prerequisite to considering Hooks stable. Can’t give you any dates though.

I’m still getting this issue in React 16.8 release. Is there a corresponding jest upgrade that needs to happen to allow shallow testing on hooks?

File a new issue with a reproducing case. Shallow rendering Hooks should work.

You’re sure you didn’t forget to update test renderer?

I figured this out as well, https://codesandbox.io/s/82qv0m8l98 is a super small repro when we get around to testing this

Eagerly awaiting this being released to alpha…

Thanks for the fix! When will this be released into alpha? Sorry for the noob question.