react enzyme test button click code example
Example 1: simulate click jest
import React from 'react';
import { shallow } from 'enzyme';
import Button from './Button';
describe('Test Button component', () => {
it('Test click event', () => {
const mockCallBack = jest.fn();
const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>));
button.find('button').simulate('click');
expect(mockCallBack.mock.calls.length).toEqual(1);
});
});
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())
})
})