Home > front end >  How can I check if element does not exist in a React test?
How can I check if element does not exist in a React test?

Time:09-21

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:

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.

CodePudding user response:

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

  • Related