reactjs - 如何使用酶对作为属性传递的元素进行断言?
问题描述
问题
假设我们有一个 React 组件Page,它呈现组件Layout并将元素SidePanel作为属性向下传递。我们如何对 Enzyme 中SidePanel的属性做出断言?
const Page = () => (
<Layout
contentLeft={
<SidePanel expanded={true} />
}
>
// ...
</Layout>
);
我试过的
由于 'contentLeft' 严格来说不是渲染道具,我们不能利用 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);
有没有更简单的方法?
解决方案
我最终通过实现一个助手“shallowProperty”解决了这个问题:
// shallowProperty.tsx
const toComponent = (
element:
| React.ReactElement<any, string | React.JSXElementConstructor<unknown>>
| undefined
) => {
const Component = () => (element as unknown) as JSX.Element;
return <Component />;
};
const shallowProperty = (
element: ReactElement<any, string | JSXElementConstructor<any>> | undefined
) => shallow(toComponent(element));
// my.test.tsx
const contentLeft = shallowProperty(
shallow(<Page />)
.find(Layout)
.prop("contentLeft")
);
const expanded = contentLeft.prop("expanded");
expect(expanded).toEqual(true);
推荐阅读
- javascript - Web 服务 C# 返回未定义的值
- python - 如何将 `tf.scatter_nd` 与多维张量一起使用
- excel - 将具有相应 ID 号的行复制到不同的工作表中
- python - How to map one dataframe to another (python pandas)?
- machine-learning - 计算最佳成本函数 - SVM
- julia - 在 Julia v.1.1.1 中使用 CPLEX 求解器构建模型时如何定义 Gap?
- c# - 如何将以前花费的时间和最近花费在同一级别上的时间相加?
- python - 从上一步和拟合数据输入到 sklearn 管道
- c# - Microsoft.AspNetCore.Identity.EntityFrameworkCore.dll 中发生“System.InvalidOperationException”
- javascript - 如何在 contenteditable 失去焦点并以编程方式重新获得焦点后再次获得选定的文本焦点