enzyme: testing stateless component in react gives - TypeError: Cannot set property event of # which has only a getter
Current behavior
Facing this issue when I try to test react stateless functional component. Test class-
it('should call callback on click', function () {
const handleSearchCallBack = (event) => {
console.log('please call this');
};
const wrapper = mount(<TextIconSearchButton handleOnClick={handleSearchCallBack} />);
wrapper.find('input').at(0).simulate('change', { target: { value: 1 } });
});
and Component -
import Button from '@material-ui/core/Button';
import SearchIcon from '@material-ui/icons/Search';
import React from 'react';
const TextIconSearchButton = ({handleOnClick}) => (
<div>
<Button
onClick={handleOnClick}
variant="contained"
color="primary"
startIcon={<SearchIcon />}
>
</Button>
</div>
);
export default TextIconSearchButton; On running a test, mocha --require @babel/register --require test/testSetup.js it continuously printed below error in a long loop Error: Uncaught [TypeError: Cannot set property event of # which has only a getter]
and then finally,
Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
Its thrown at this line from react-dom.js if (typeof window.event !== ‘undefined’ && window.hasOwnProperty(‘event’)) { window.event = windowEvent; }
This happens when I do enzyme’s mount instead of shallow. I tried ReactDOM.render from test-utils but same result is popping up.
I tried upgrading to 17.0.1 react version but that endless loop gets worst and test case never exits.
Expected behavior
should able to mount functional component
Your environment
API
- shallow
- mount
Version
library | version |
---|---|
enzyme | 3.11.0 |
react | 16.8.2 |
react-dom | 16.8.2 |
react-test-renderer | |
adapter (below) |
Adapter
- enzyme-adapter-react-16
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Comments: 15 (7 by maintainers)
You are right! Also not sure but I will choose not to test their library in detail! Other components where I am using my own components as a child are working just fine(till now!). Thanks for your help!
So, in that debug output, there’s no
MenuItem
anything listed. However, I notice that in your component code, you haveimport MenuItem from '@material-ui/core/MenuItem';
but in your test code you haveimport {MenuItem} from '@material-ui/core';
. Those likely aren’t the same MenuItem.What I’m asking is, after the
const wrapper = mount(
line, can you addconsole.log(wrapper.debug())
and share the resulting output here.