'React Testing Library - Unable to find the element with data-testid

I am following the docs for react-testing-library to find if the element with data-testid attribute is rendered or not.

The react-testing-library is not able to find the element even though it exists.

TEST

test('Renders step based on the active step', () => {
    render(<RenderStep />, { initialState: { implOnboard: initialState } });
  });
  expect(screen.getByTestId('step-1')).toBeDefined(); // 👉 THROWS ERROR ❌
}

COMPONENT

 // redux
  const { activeStep } = useSelector((state) => state.implOnboard);

  const renderStep = () => {
    switch (activeStep) {
      case 1:
        console.log('Rendering this 🔥'); // 👈 THIS IS GETTING LOGGED TOO!
        return (
          <div data-testid="step-1">
            <StepOne />
          </div>
        );
      case 2:
        return (
          <div data-testid="step-2">
            <StepTwo />
          </div>
        );
    }
  };
  return <React.Fragment>{renderStep()}</React.Fragment>;

ERROR

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


Solution 1:[1]

Please use the queryByTestId instead getByTestId for the case. It will work.

Solution 2:[2]

Adding to Elena's response, we need to use queryByTestId because, queryByTestId returns null value instead of throwing error unlike getByTestId. Here's the image that explains when to use different methods.

enter image description here

Reference - https://www.youtube.com/watch?v=Yghw9FkNGsc&list=PL4cUxeGkcC9gm4_-5UsNmLqMosM-dzuvQ&index=5&ab_channel=TheNetNinja

Solution 3:[3]

The answer from Elena is wrong and just masks the error. Using queryByTestId will return null if the element is not found, instead of an error when using getByTestId, and the assertion will actually be:

  expect(null).toBeDefined();

and this WILL pass. This is not testing anything. toBeDefined() fails only if the element is equal to undefined and it passes for everything else.

If OP wants to actually check if that element is NOT present they should do:

  expect(screen.queryByTestId('step-1')).not.toBeInTheDocument();

The original error from OP is probably happening because the expect is outside the test block.

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 Elena Lembersky
Solution 2 Sandeep Amarnath
Solution 3