react ezyme 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 ezyme simulate click
import React from "react";
class Button extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
this.onClick = this.onClick.bind(this);
}
onClick() {
this.setState({ count: 1 });
}
renderState() {
return this.state.count;
}
render() {
return (
<div>
<button onClick={this.onClick}>{this.count}</button>
</div>
);
}
}
export default Button;
import React from "react";
import { mount } from "enzyme";
import Button from "./Button";
describe("button test", () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<Button />);
});
it("test increment button", () => {
wrapper.find("button").simulate("click");
wrapper.setState({ count: 3 });
expect(wrapper.state("count")).toBe(3);
expect(wrapper.instance().renderState()).toBe(3);
});
});