react enzyme simulate click sub component code example
Example 1: react enzyme simulate click sub component
//Counter.js
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
//App.js
import React from 'react'
import Counter from './Counter'
const App = (props) => {
return (
<>
<Counter />
</>
)
}
export default App
//App.test.js
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())
})
})
Example 2: react enzyme simulate click sub component
/**
* This test passes with or without the onMouseOver/onMouseLeave handlers.
* In a real browser, onClickMock is not called without those handlers.
*/
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);
});