首页 > 解决方案 > 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();

标签: reactjsreact-testing-library

解决方案


你可以将它包装在一个返回 JSX 的函数中:

const hasProperties = () => true;
const RenderOrNOt = () => hasProperties() ? (<TargetComponent />) : null; // Use a function 
const { container } = render(<RenderOrNOt/>);
expect(container.querySelector('label')).not.toBeNull();

尽管如此,最好的方法是渲染容器组件以进行条件渲染并检查是否TargetComponent在 DOM 中。


推荐阅读