I have a simple React component that uses the useState hook. This component works correctly in the application, but my Jest test gives me the error "Hooks can only be called inside the body of a function component". As far as I can tell, I am calling useState correctly and, again, it works fine when I run the application.
I am using version 16.8.4 of both react and react-dom, as verified by npm ls.
Here is the component in its entirety:
import React, {useState} from 'react';
import './ExampleComponent.css';
function ExampleComponent(props) {
const [count, setCount] = useState(0);
const handler = () => setCount(count + 1);
return (
<div className='example-component'>
<span>This component is a test</span>
<button onClick={handler}>Test</button>
<input readOnly={true} value={count}></input>
</div>
);
};
export default ExampleComponent;
And here is the corresponding Jest test (using Enzyme):
import React from 'react';
import ExampleComponent from './ExampleComponent';
describe('<ExampleComponent />', () => {
const options = {
targetElementId: 'fake-element-id'
};
const wrapper = shallow(<ExampleComponent options={options} />);
it('renders a div', () => expect(wrapper.find('div').exists()).toBe(true));
});
I had read in some sources that Enzyme does not work with hooks, but I have a co-worker who is not having the problem. I have compared our package.json files and webpack configs and can find no differences.
mountinstead ofshallow? - zsgomori