reactjs - react testing library render component conditionally
问题描述
I want to test if a component renders or not based on a condition using the react testing-library not enzyme.
This is my component source code:
{hasProperties() ? (<TargetComponent />) : null}
How can I pass that condition to a test. What I tried is that but obviously without success:
const hasProperties = () => true;
const renderOrNOt = hasProperties() ? (<TargetComponent />) : null;
const { container } = render(renderOrNOt);
expect(container.querySelector('label')).not.toBeNull();
解决方案
你可以将它包装在一个返回 JSX 的函数中:
const hasProperties = () => true;
const RenderOrNOt = () => hasProperties() ? (<TargetComponent />) : null; // Use a function
const { container } = render(<RenderOrNOt/>);
expect(container.querySelector('label')).not.toBeNull();
尽管如此,最好的方法是渲染容器组件以进行条件渲染并检查是否TargetComponent
在 DOM 中。
推荐阅读
- android - 布局文件中引用的类 androidx.constraintlayout.widget.ConstraintLayout 在项目中找不到或库错误消息
- r - 如何在不上网的情况下安装 gert 包
- r - R中基于点颜色代码的梯度图图例
- c++-cli - C++ CLI - 有没有办法转换/转换 cli::array
^ 到 LPCSTR *? - javascript - 为什么这个 fetch 错误处理不起作用?
- django - 带有 3 个选项的 Django Filter BooleanFilter - True、False 和 Both
- c++ - 是否允许比较 static_assert 中静态类字段的指针?
- docker - 如何避免将目录名称自动添加到 docker-compose yml 中指定的多个 docker 卷?
- python - Pandas 按范围线性减少列值
- filter - MDX - 使用最早的年月查找最早的日期