React Testing Library - Unable to find the element with data-testid
Asked Answered
C

5

46

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"]
Clammy answered 9/6, 2021 at 4:24 Comment(2)
In your test file just add this console.log(screen.debug(null, Infinity)); before your expect and check whether you are seeing the DOM getting printed correctly . – Indulgence
Any reason why the expect statement is outside the test() block? – Macmacabre
I
70

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

Innocence answered 8/7, 2021 at 10:11 Comment(3)
Any reason why it works with queryByTestId and not with getByTestId? – Dreadful
@ArpitGupta its not actually working, its just ignoring the error, I console logged queryByTestId it returned null which means the element is still not found but this function does not throw an error instead returns null due to which test cases are passing. – Rochellrochella
Like Kashan said, This is wrong and I explain why on my answer – Arboriculture
A
48

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.

Arboriculture answered 31/3, 2022 at 22:32 Comment(2)
This is the appropriate answer. Thanks! – Tachylyte
You can find more information on those methods in the docs, they explain differences between 'get' 'query' and 'find' – Pythagoras
H
24

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

Hausner answered 20/12, 2021 at 3:43 Comment(1)
Incorrect, it hides the error because expect(null).toBeDefined() returns true – Pythagoras
T
4

For those using React Native Web, you will need to use testID which will compile down to data-testid on the element. It needs to be on a react native element not your custom one (pass it through as a prop and put it on a View, etc.).

Terrie answered 16/12, 2022 at 1:14 Comment(0)
S
0

In my case it was just an typo instead of data-testid i wrote date-testid

Secure answered 17/5, 2023 at 16:11 Comment(0)

© 2022 - 2024 β€” McMap. All rights reserved.