simulate click jest
Simulate Click Jest
If you want to simulate a click using Jest, you can use the simulate
method provided by the Enzyme library that is compatible with Jest. It allows you to simulate various events, including clicks, key presses, and form submissions.
Example:
import { shallow } from 'enzyme';
import MyComponent from './MyComponent';
describe('MyComponent', () => {
it('should simulate click', () => {
const wrapper = shallow(<MyComponent />);
const button = wrapper.find('button');
button.simulate('click');
expect(wrapper.find('.is-clicked')).toHaveLength(1);
});
});
In this example, we use the shallow
method from Enzyme to render our MyComponent
component. Then we locate the button element using the find
method and simulate the click event using the simulate
method. Finally, we assert that after the click event, our component has a CSS class of is-clicked
.
If you want to simulate a click on a specific element, you can pass an event object as the second parameter to the simulate
method. For example:
button.simulate('click', { target: { value: 'test' } });
This will simulate a click event on the button element with a target value of 'test'.
Another way to simulate a click in Jest is by using the fireEvent
method provided by the @testing-library/react
library. Here's an example:
import { fireEvent, render } from '@testing-library/react';
import MyComponent from './MyComponent';
describe('MyComponent', () => {
it('should simulate click', () => {
const { getByText } = render(<MyComponent />);
const button = getByText('Click me');
fireEvent.click(button);
expect(button.classList.contains('is-clicked')).toBe(true);
});
});
In this example, we use the render
method from @testing-library/react
to render our component, locate the button element using the getByText
method, simulate the click event using the fireEvent.click
method, and assert that the button has a CSS class of is-clicked
.