如何使用Enzyme对作为属性传递的React组件元素执行属性断言?
问题描述
假设我们有一个React组件Page,它渲染Layout组件并将SidePanel元素作为属性传递,请问该如何在Enzyme中对SidePanel的属性进行断言?
const Page = () => ( <Layout contentLeft={ <SidePanel expanded={true} /> } > // ... </Layout> );
已尝试方案
由于contentLeft严格来说不属于render prop,无法使用Enzyme的renderProp功能,运行以下代码会抛出类型错误:
const wrapper = shallow(<Page />) .find(Layout) .renderProp("contentLeft")(); // TypeError: ShallowWrapper::renderProp(): expected prop "contentLeft" to contain a // function, but it holds "object" const expanded = wrapper.find(SidePanel).prop("expanded"); expect(expanded).toEqual(true);
当前可用方案
以下方案可正常运行,但实现不够优雅:
const contentLeft = shallow(<Page />) .find(Layout) .prop("contentLeft"); const ContentLeft = () => contentLeft; const wrapper = shallow(<ContentLeft />); const expanded = wrapper.find(SidePanel).prop("expanded"); expect(expanded).toEqual(true);
请问是否存在更简便的实现方式?
解决方案
有两种更简洁的实现方式,不需要额外定义临时组件:
方式1:直接读取React元素属性
contentLeft本身就是已经创建完成的React元素对象,自带props属性可以直接访问,不需要再走渲染流程:
const sidePanel = shallow(<Page />) .find(Layout) .prop("contentLeft"); expect(sidePanel.props.expanded).toBe(true);
方式2:直接将元素传入shallow方法
如果你需要使用Enzyme的API做更复杂的查找/断言,可以直接把拿到的React元素传给shallow,不需要额外包裹函数组件:
const contentLeft = shallow(<Page />) .find(Layout) .prop("contentLeft"); const wrapper = shallow(contentLeft); expect(wrapper.find(SidePanel).prop("expanded")).toBe(true);
原理解释
Enzyme的renderProp方法只支持处理值为函数类型的prop,你当前场景下contentLeft是直接传递的React元素对象,不需要调用渲染逻辑,直接操作元素本身即可。
内容的提问来源于stack exchange,提问作者Luc
相关产品推荐
相关产品推荐

