A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/enzymejs/enzyme/issues/1938 below:

Invariant Violation · Issue #1938 · enzymejs/enzyme · GitHub

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 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

eirikhm, Taranys, jestanoff, vince91, andiwinata and 34 more


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4