How to find a React component inside an element with specific class using enzyme?

僤鯓⒐⒋嵵緔 提交于 2021-01-29 07:59:28

问题


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.


回答1:


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



回答2:


The type of element isn't a Button, thats the component name. It is probably a button or input. You can do it like this depending on what element type the node is:

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

To make this more specific you could always add a class to the button.

Or, per the documentation, if you'd like to you can target it by inputting the component to the test and then finding it that way:

import Bar from '../components/Foo';

const wrapper = shallow(<MyComponent />);
wrapper.find(Bar).simulate("click");

Finally, without any additional imports you can use the display name of the component like so:

const baz = shallow(<MyComponent />);
baz.find('Button').simulate("click");


来源:https://stackoverflow.com/questions/55451529/how-to-find-a-react-component-inside-an-element-with-specific-class-using-enzyme

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!