Ad

Query A Button With Specific Text

- 1 answer

I have a (Jest) test to determine if a button exists:

it('renders a signup button', () => {
  expect(sut.getByText('Sign up for free')).toBeDefined()
})

This test because there is both a button AND heading with "Sign up for free" text in the component.

Screenshot showing both a heading and button with "Sign up for free" text

A testid could be added to the button, but I'd prefer to follow the react-testing-library principle of simulating user behaviour.

I feel it's legitimate a user would want to "click the button labelled 'Sign up for free'". In this situation, specifying the type of HTML element makes sense as a <button /> is a distinctive element to the user, as opposed to be <h2 /> vs <h3 />.

How can I query for a button element labelled "Sign up for free"? For example can getByText() be further limited by a query selector?

Ad

Answer

I'm surprised no one here gives the most idiomatic answer yet. You can use getByRole() and pass an accessible name. The accessible name is the text of the button or the value of aria-label attribute.

It can be used to query a specific element if multiple elements with the same role are presented on the screen.

Text button

<button>Text Button</button>
screen.getByRole('button', {
  name: /text button/i
})

Icon button

<button aria-label='edit'>
  <edit-icon />
</button>
screen.getByRole('button', {
  name: /edit/i
})
Ad
source: stackoverflow.com
Ad