I have a React component that returns its children
to be rendered by React if the prop isTrue
is truth-y. If its prop isTrue
is false-y, then the component returns null
, and React doesn’t render anything.
I need to test it as a component, mount it, pass the prop, and test if it’s children is getting rendered when the prop isTrue
is truth-y, or we are getting null
if isTrue
is false-y.
Here is my component:
JavaScript
x
8
1
const RenderIf = ({ isTrue, children }) => {
2
if (isTrue) {
3
return children;
4
}
5
return null;
6
}
7
export default RenderIf
8
Advertisement
Answer
I’d think in this case it is probably ok to test the whole html. react-testing-library wraps your content with a single div so you could something like that:
JavaScript
1
3
1
const { container } = render(<MyComponent ifTrue={false}>Content</MyComponent>);
2
expect(container.innerHTML).toBe('<div></div>');
3
If you don’t like this approach, you can still render a children with a test-id / text and query it to see if it’s present.