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.