[SOLVED] React Testing | Check if element does not exist


This Content is from Stack Overflow. Question asked by Gustav Vingtoft

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 are empty. I therefeore expect my child componnet test-id to be null on initial render, when I render my parents container.

Parent component:

const ParentComponent = () => {

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

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

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

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

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

Child component:

const ChildComponent = () => {

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

Unit test:

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

      <ParentComponent />



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 whta I want it to be.


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

Answered by Andrei Belokopytov

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5.CC BY-SA 3.0.CC BY-SA 4.0.

people found this article helpful. What about you?