【问题标题】:How to find a React component inside an element with specific class using enzyme?如何使用酶在具有特定类的元素中找到 React 组件?
【发布时间】:2019-04-01 09:07:12
【问题描述】:

我正在尝试使用 Jest 和 Enzyme 测试 React 组件。我想在具有特定类名的 div 内的 Button 组件上模拟单击事件。我无法检索 Button 节点。

我的组件中有以下标记

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

我试过了

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

我希望找到 Button 组件,但我得到了 0 节点。

【问题讨论】:

    标签: reactjs enzyme


    【解决方案1】:

    试试下面的代码

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

    编辑 试试下面的代码:

    expect(component
            .find(Button)
            .closest('.settings'))
            .simulate("click");
    

    【讨论】:

    • 如果我只有一个 Button 组件,这将起作用。或者,我将不得不写类似component.find(Button).at(3).simulate("click"); 的东西。这并不理想,因为每次 Button 的顺序更改时我都必须更改此测试。我想要一种更具体的方式来检索按钮,因此,这仍然不能回答我的问题。
    【解决方案2】:

    元素的类型不是Button,这是组件名称。它可能是buttoninput。根据节点的元素类型,您可以这样做:

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

    为了使这一点更具体,您始终可以向按钮添加一个类。

    或者,per the documentation,如果您愿意,您可以通过将组件输入到测试中然后以这种方式找到它来定位它:

    import Bar from '../components/Foo';
    
    const wrapper = shallow(<MyComponent />);
    wrapper.find(Bar).simulate("click");
    

    最后,无需任何额外的导入,您就可以像这样使用组件的显示名称:

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

    【讨论】:

      猜你喜欢
      • 2023-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-22
      • 1970-01-01
      • 2013-06-03
      • 1970-01-01
      • 2022-10-07
      相关资源
      最近更新 更多