enzyme render simulate click code example
Example 1: react enzyme simulate click
function App() {
const [count, setCount] = React.useState(0)
const onClick = () => {
setCount((prevState) => prevState + 1)
}
return (
<div>
<button onClick={onClick}>{count}</button>
</div>
)
}
export default App
describe('Counter Group', () => {
it('calls incCounter function when button is clicked', () => {
const wrapper = shallow(<App />)
const initClickCount = 2
for (let i = 0; i < initClickCount; i++) {
wrapper.find('button').simulate('click')
}
expect(wrapper.find('button').text()).toContain(2)
console.log(wrapper.debug())
})
})
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())
})
})