Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React Testing | Check if element does not exist

I want to test that on initial render of the parent component, there are no child components rendered in the document.

On every press of the button, the parent component generates a child component within it. On init, the child component array is empty. I therefore expect my child componet test-id to be null on initial render, when I render my parent component.

Parent component:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const ParentComponent = () => {

  const [childComponentsArray, setChildComponentsArray] = useState([]);

  const createChildComponent = () => {
    const objToAdd = {
      // Generate uuid for each component
      uuid: uuid()
    };

    setChildComponentsArray([...childComponentsArray, objToAdd]);
  };

  return (
    <div>
      {childComponentsArray.length > 0 && <div>
        {childComponentsArray.map(() => {
          return <div className={'child-item'}>
            <ChildComponent />
          </div>;
        })}
      </div>}

      <ButtonContainer variant={'secondary'} label={'+ ' + component.addLabel}
                       onClick={() => createChildComponent()}
                       />
    </div>
  );
};

Child component:


const ChildComponent = () => {

return (
<div data-testid={'childComponentTestId'}>
<p> I'm in child component! </p>
</div
)
}

Unit test:

test('on render, no child items are visible', () => {

  render(
    <RecoilRoot>
      <ParentComponent />
    </RecoilRoot>
  )

  expect(screen.getByTestId('childComponentTestId')).toBeNull();

});

When executing my test I get the following error in my unit test:

TestingLibraryElementError: Unable to find an element by: [data-testid="childComponentTestId"]

I find this error a bit of a paradox, since that is exactly what I want it to be.

note
Passing the data-testid as a prop does not help.
Using .not.toBeInDocument() does not work.
Using .toBeUndefined() does not work either.

>Solution :

You should use queryByTestIt as it returns null if object is not found.
See more on the documentation site.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading