'How to test if React component is returning null or its children using React Testing Library?

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


Solution 1:[1]

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.

Solution 2:[2]

expect(container).toBeEmptyDOMElement()

Solution 3:[3]

import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
//...

describe('TestHistory', () => {
  it('should render nothing if there are no history entries', () => {
    // ARRANGE
    // ACT
    const { container } = render(
      <TestHistory version={1} versionHistory={[]} datasetType={DatasetType.VALIDATION} />,
    );

    // ASSERT
    expect(container).toBeEmptyDOMElement();
  });
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Axnyff
Solution 2 alastairtree
Solution 3