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:
const RenderIf = ({ isTrue, children }) => { if (isTrue) { return children; } return null; } export default RenderIf
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:
const { container } = render(<MyComponent ifTrue={false}>Content</MyComponent>); expect(container.innerHTML).toBe('<div></div>');
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.