wrapper.simulate code example

Example 1: react enzyme simulate click

// App.js
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

//App.test.js
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

// button.js
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;

//button.test.js
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", () => {
    // click event inc from zero to one
    wrapper.find("button").simulate("click");
    // replace value click event with new value to 3
    wrapper.setState({ count: 3 });
    // expect value is correct or not
    expect(wrapper.state("count")).toBe(3);
    expect(wrapper.instance().renderState()).toBe(3);
  });
});