简体   繁体   中英

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
expect(container).toBeEmptyDOMElement()
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(); }); });

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.

expect(container.innerHTML).toEqual('');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM