Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"]
like image 564
Karan Kumar Avatar asked Jun 09 '21 04:06

Karan Kumar


People also ask

What is data testID react?

data-testid is an attribute used to identify a DOM node for testing purposes. It should be used as a handler to the test code. We need to make sure its value is unique. Therefore, we do not cause conflicts between components.

What is getByTestId?

Test IDs. getByTestId : The user cannot see (or hear) these, so this is only recommended for cases where you can't match by role or text or it doesn't make sense (e.g. the text is dynamic). As a fallback there also Manual Queries. Follow this answer to receive notifications.

What is testID in react native?

So in easy language the testID prop is used as a unique identifier ID for UI Automation Testing Script.

What is a testing library?

The Testing Library family of libraries is a very light-weight solution for testing without all the implementation details. The main utilities it provides involve querying for nodes similarly to how users would find them. In this way, testing-library helps ensure your tests give you confidence in your UI code.


Video Answer


3 Answers

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

like image 118
Elena Lembersky Avatar answered Oct 22 '22 16:10

Elena Lembersky


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.

like image 17
Luiz Avila Avatar answered Oct 22 '22 18:10

Luiz Avila


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

Sometimes you get an error even when using this queryBy, so please check other code before this statement.

enter image description here

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

like image 10
Sandeep Amarnath Avatar answered Oct 22 '22 17:10

Sandeep Amarnath