Question

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"]
 46  115648  46
1 Jan 1970

Solution

 69

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

2021-07-08

Solution

 50

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.

2022-03-31