我有一个 Jest/ enzyme 测试,它在组件周围创建一个ShallowWrapper,找到指定的semantic-ui-react按钮(通过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);
});
当我刚刚拥有按钮时,此测试有效。当我添加弹出窗口并将按钮放入触发器 Prop 中时,我收到错误,因为找不到#special-btn。
Error: Method “props” is only meant to be run on a single node. 0 found instead.
该组件的 enzyme 快照显示弹出窗口如下所示:
<Popup
content="Popup Words"
on="hover"
position="top left"
trigger={
<Button
id="special-btn"
onClick={[Function]}
>
a button
</Button>
}
/>
我需要我的测试才能再次运行。如何在测试中再次访问 #special-btn 以便我可以对其调用 .simulate('click') ?
最佳答案
这对我有用,尽管没有相关文档:
import {shallow, ShallowWrapper} from "enzyme";
it('shows the thing when the button is clicked', () => {
const wrapper = shallow(<MyComponent />);
const button = new ShallowWrapper(
wrapper.find('Popup').prop('trigger'), wrapper
);
button.simulate('click', { preventDefault() {} });
expect(wrapper.find('.special-thing').exists()).toBe(true);
});
换句话说:
- 找到
Popup
组件。 - 获取在其
trigger
属性中渲染的组件。请注意,这还不是一个浅层包装器,因此还没有精美的 API。 - 使用
ShallowWrapper
手动创建包装器(传递第二个参数很重要)。 - 现在您可以访问所有 enzyme API 来与按钮交互。
注意,似乎您可以避免使用构造函数并使用 wrap()相反的实用方法(也没有记录):
const button = wrapper.wrap(wrapper.find('Popup').prop('trigger'));
关于reactjs - 如何使用 ShallowWrapper 来查找作为 prop 存储在另一个 React 组件中的 React 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45849936/