Ad

How To Find A React Component Inside An Element With Specific Class Using Enzyme?

- 1 answer

I am trying to test a React component using Jest and Enzyme. I want to simulate a click event on a Button component which is inside a div with a specific class name. I can't retrieve the Button node.

I have the following markup in my component

<div className="settings">
    <Button
        onClick={() => this.toggleSettingsModal(true)}
        buttonStyle={ButtonStyle.Primary}>
        Settings
    </Button>
</div>

I have tried

const component = shallow(<MyComponent />);
component.find(".settings[Button]").simulate("click");

I expect to find the Button component, but I get 0 nodes.

Ad

Answer

Try the code below

import { shallow } from 'enzyme'
import MyComponent from './MyComponent'

describe('<MyComponent />', () => {
    it('simulates click events', () => {
        const component = shallow(<MyComponent />);
        component.find(Button).simulate("click");
    });
});

EDIT Try the code below:

expect(component
        .find(Button)
        .closest('.settings'))
        .simulate("click");
Ad
source: stackoverflow.com
Ad