0

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

<body>
        <div>
          <span
            class="button-group"
          />
        </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.

2
  • 1
    I think the write way is expect(container.firstChild).toHaveClass( 'button-group' ) Commented May 4, 2022 at 13:34
  • gets fixed by this same answer => stackoverflow.com/a/65948977/14409895 Commented Sep 8, 2022 at 14:57

1 Answer 1

3

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

<div>
    <span data-testid="span-id"
      class="button-group"
    />
  </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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I am trying like this: ```test( 'should have ButtonGroup class', () => { render( <ButtonGroup /> ); screen.debug(); expect( screen.getByTestId( 'button-group-id' ).toHaveClass( 'button-group' ) ); } ); But Getting that toHaveClass is not a function: Direct Link
There is an issue with brackets. it should be expect(screen.getByTestId('button-group-id')).toHaveClass('button-group');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.