enzyme simulate is not a function code example
Example 1: react enzyme simulate click sub component
const data = [
{title: 'Option 1', description: 'a cool option'}
];
it('should invoke a childs onClick handler when the child is clicked', () => {
const onClickMock = jest.fn();
const component = shallow(
<Dropdown
buttonContent='Dropdown'>
<ul>
{ data.map((item, index) => {
return (
<li
key={ index }
onClick={ onClickMock }
data-test-section={ `dropdown-item-${index}` }>
{ item.title }
</li>
);
})
}
</ul>
</Dropdown>
);
component.find('button').simulate('click');
component.find('[data-test-section="dropdown-item-1"]').simulate('click');
expect(onClickMock.mock.calls.length).toBe(1);
});
Example 2: react enzyme simulate click sub component
import React from 'react'
function Counter() {
const [count, setCount] = React.useState(0)
const onClick = () => setCount((prevState) => prevState + 1)
return (
<div>
<button onClick={onClick}>{count}</button>
</div>
)
}
export default Counter
import React from 'react'
import Counter from './Counter'
const App = (props) => {
return (
<>
<Counter />
</>
)
}
export default App
import React from 'react'
import { mount } from 'enzyme'
import App from './App'
import Counter from './Counter'
describe('Counter Group', () => {
it('calls incCounter function when button is clicked', () => {
const wrapper = mount(<App />)
const subComponent = wrapper.find(Counter)
const initClickCount = 2
expect(subComponent.find('button').exists()).toBeTruthy()
for (let i = 0; i < initClickCount; i++) {
subComponent.find('button').simulate('click')
}
expect(subComponent.find('button').text()).toContain(2)
console.log(wrapper.debug())
})
})