simulate onclick enzyme code example
Example 1: react enzyme simulate change
import React from 'react'
const App = (props) => {
return (
<>
<input type='text' name='username' value={props.username} onChange={props.onChange} />
<input type='email' name='email' value={props.email} onChange={props.onChange} />
</>
)
}
export default App
import React from 'react'
import { shallow } from 'enzyme'
import App from './App'
it('change value', () => {
const state = { username: 'joe', email: '[email protected]' }
const props = {
username: state.username,
email: state.email,
onChange: (e) => {
state[e.target.name] = e.target.value
}
}
const wrapper = shallow(<App {...props} />)
expect(wrapper.find('input').at(0).prop('value')).toEqual('joe')
expect(wrapper.find('input').at(1).prop('value')).toEqual('[email protected]')
wrapper
.find('input')
.at(0)
.simulate('change', { target: { name: 'username', value: 'john doe' } })
expect(state.username).toEqual('john doe')
wrapper
.find('input')
.at(1)
.simulate('change', { target: { name: 'email', value: '[email protected]' } })
expect(state.email).toEqual('[email protected]')
console.log(wrapper.debug())
})
Example 2: 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())
})
})