如何使用ShallowWrapper酶来查找作为prop存储在另一个React Component中的React Component?

问题描述 投票:2回答:3

我有一个玩笑/酶测试,该测试在组件周围创建ShallowWrapper,找到指定的语义UI反应按钮(按id),模拟对按钮的单击,然后查看该单击是否切换了某些内容。

示例JSX:

<Popup
  trigger={<Button onClick={this.toggleShowThing} id="special-btn">a button</Button>}
  content="Popup Words"
/>
{this.state.showThing &&
  <div className="special-thing">The Thing's Words</div>
}

样本测试:

it('shows the thing when the button is clicked', () => {
  const wrapper = shallow(<MyComponent />);
  wrapper.find('#special-btn').simulate('click', { preventDefault() {} });
  expect(wrapper.find('.special-thing').exists()).toBe(true);
});

此测试在我只有Button时起作用。当我添加弹出窗口并将按钮放入触发道具时,我收到一个错误,因为找不到#special-btn。

错误:方法“ props”仅应在单个节点上运行。找到0个。

该组件的酶快照显示弹出窗口看起来像这样:

<Popup 
  content="Popup Words"
  on="hover"
  position="top left"
  trigger={
    <Button
      id="special-btn"
      onClick={[Function]}
    >
      a button
    </Button>
  }
/>

我需要我的测试才能再次工作。如何在测试中再次访问#special-btn,以便可以对其调用.simulate('click')?

reactjs jestjs enzyme semantic-ui-react
3个回答
0
投票

假设Popup是已经测试过的某些第三方组件,我将通过以下方式进行测试:


0
投票

问题是您无法做到。您需要重写测试。您的按钮现在由Popup组件包裹,因此您无权访问它。但是您可以将选择器移至Popup并测试单击弹出窗口是否触发了所需的更改。别无选择。


0
投票

这是对我有用的,尽管没有相关文档:

© www.soinside.com 2019 - 2024. All rights reserved.