Categories
React Answers

How to simulate a button click in Jest and JavaScript?

Spread the love

Sometimes, we want to simulate a button click in Jest and JavaScript.

In this article, we’ll look at how to simulate a button click in Jest and JavaScript.

How to simulate a button click in Jest and JavaScript?

To simulate a button click in Jest and JavaScript, we call the Enzyme simulate method.

For instance, we write

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);
  });
});

to call shallow to shallow mount the Button component.

Then we call find to find the button element and call simulate with 'click' to simulate a click on it.

Finally, we use expect to check what we expect.

Conclusion

To simulate a button click in Jest and JavaScript, we call the Enzyme simulate method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *