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.

Testing Hooks with shallow: Invariant Violation

See original GitHub issue

Current behavior

When testing component which contains newly released React Hooks using shallow, it crashes: Invariant Violation: Hooks can only be called inside the body of a function component.

Everything works fine at run time or when testing with render:

My test component:

import * as React from 'react';

function Test() {
    const [myState, setMyState] = React.useState('Initial state');

    const changeState = () => setMyState('State updated');

    return (
        <div>
            {myState}
            <button onClick={changeState}>Change</button>
        </div>
    );
}

export default Test;

My test file:

import { shallow } from 'enzyme';
import * as React from 'react';
import Test from './Test';

it('renders without crashing', () => {
    const comp = shallow(<Test />);

    expect(comp.find('Test')).toMatchSnapshot();
});

Error stack trace:

Invariant Violation: Hooks can only be called inside the body of a function component.

    at invariant (node_modules/react/cjs/react.development.js:125:15)
    at resolveDispatcher (node_modules/react/cjs/react.development.js:1450:28)
    at Object.useState (node_modules/react/cjs/react.development.js:1473:20)
    at Test (src/Test.tsx:4:11)
    at node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:440:38
    at ReactShallowRenderer.render (node_modules/react-test-renderer/cjs/react-test-renderer-shallow.development.js:412:39)
    at node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:444:37
    at withSetStateAllowed (node_modules/enzyme-adapter-utils/build/Utils.js:137:16)
    at Object.render (node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:443:70)
    at new ShallowWrapper (node_modules/enzyme/build/ShallowWrapper.js:206:22)
    at Object.shallow (node_modules/enzyme/build/shallow.js:21:10)
    at Object.<anonymous> (src/Test.test.tsx:6:18)
        at new Promise (<anonymous>)
    at Promise.resolve.then.el (node_modules/p-map/index.js:46:16)
    at process._tickCallback (internal/process/next_tick.js:68:7)

Expected behavior

Tests should run

Your environment

Fresh create-react-app-typescript install with react 16.7.0-alpha-0

API

  • shallow
  • mount
  • render

Version

library version
enzyme 3.8.0
react 16.7.0-alpha.0
react-dom 16.7.0-alpha.0
react-test-renderer
adapter (below)

Adapter

  • enzyme-adapter-react-16
  • enzyme-adapter-react-16.3
  • enzyme-adapter-react-16.2
  • enzyme-adapter-react-16.1
  • enzyme-adapter-react-15
  • enzyme-adapter-react-15.4
  • enzyme-adapter-react-14
  • enzyme-adapter-react-13
  • enzyme-adapter-react-helper
  • others ( )

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:39
  • Comments:79 (31 by maintainers)

github_iconTop GitHub Comments

62reactions
bob-leecommented, Jun 11, 2019

I had the same issue and the reason was multiple versions of react-test-renderer

$ yarn why react-test-renderer yarn why v1.16.0 [1/4] Why do we have the module “react-test-renderer”…? [2/4] Initialising dependency graph… [3/4] Finding dependency… [4/4] Calculating file sizes… => Found “react-test-renderer@16.8.6” info Has been hoisted to “react-test-renderer” info This module exists because it’s specified in “dependencies”. => Found “enzyme-adapter-react-16#react-test-renderer@16.2.0” info This module exists because “enzyme-adapter-react-16” depends on it. Done in 1.74s.

For some reason, enzyme-adapter-react-16 had an old react-test-renderer@16.2.0 as its own dependency. I had to remove and add them back:

yarn remove enzyme enzyme-adapter-react-16 react-test-renderer yarn add enzyme enzyme-adapter-react-16 react-test-renderer

39reactions
ljharbcommented, Dec 12, 2018

Hooks are not yet in a non-alpha version, and are definitely not yet supported in enzyme.

I’d suggest waiting to use them until they’re not experimental.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Shallow Testing Hooks with Enzyme - Carbon Five Blog
The trick to shallow testing hooks like useEffect is to use spies. The examples here are specifically for Jest, but they should work...
Read more >
How to test React Hooks - LogRocket Blog
The goal of this article is to provide a practical guide on testing React Hooks using tools such as React Testing Library, Jest,...
Read more >
Fix Invalid Hook Call Warning in React Tests - Sinistra
Fix Invalid Hook Call Warning in React Tests ... "Invariant Violation: Hooks can only be called inside the body of a function component....
Read more >
React / Enzyme: Invariant Violation error when running Jest ...
I have a React / Redux component and am trying to write a basic test but get the following error: Invariant Violation: ReactShallowRenderer...
Read more >
React Hooks Unit Testing using Shallow - Medium
React Hooks Unit Testing using Shallow · The shallow method allows us to render a single component that we are testing. · It...
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