Home > Mobile >  Checking for a class in React testing library
Checking for a class in React testing library

Time:05-06

I have a class called button-group that is rendered like this:

<body>
        <div>
          <span
            
          />
        </div>
      </body>

Now, How do I check/query for the presence of the button-group class? I have written:

const { container } = render( <ButtonGroup /> );
expect( container.firstChild.toHaveClass( 'button-group' ) );

But this test is failing for some reason, thank you.

CodePudding user response:

One of the proper ways for testing this would be as follows:

<div>
    <span data-testid="span-id"
      
    />
  </div>

And testcase as follows:

render( <ButtonGroup /> );
expect(screen.getByTestId('span-id')).toHaveClass('button-group') ;

We should not directly refer to the node for testing. Have a look at this doc as well https://github.com/testing-library/eslint-plugin-testing-library/blob/main/docs/rules/no-node-access.md

  • Related