Sometimes, we want to simulate a button click in Jest.
In this article, we’ll look at how to simulate a button click in Jest.
How to simulate a button click in Jest?
To simulate a button click in Jest, we can call the 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 mount the Button component.
Then we call find with 'button' to find the button element.
And then we call simulate with 'click' to simulate a click on it.
Then we call expect to check that the mockCallBack has been called once by checking mockCallBack.mock.calls.length.
Conclusion
To simulate a button click in Jest, we can call the simulate method.