'Query a button with specific text
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.
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?
Solution 1:[1]
You can pass options to your query to change its default behavior:
getByText('Sign up for free', { selector: 'button' })
You can find the full documentation here
Solution 2:[2]
You can do it like this:
getByText('Sign up for free').closest('button')
You can read more about closest from here
Solution 3:[3]
If your query returns multiple html elements, you can also use:
const elements = getAllByText('Sign up for free');
This will return an array of elements that match the query. Then if you know which element you need, you can access like this:nodes[1]
You can add the word 'All' to the different selectors to get an array of all matching queries (getAllByRole, queryAllByText, etc.)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Giorgio Polvara - Gpx |
| Solution 2 | Abdullah Danyal |
| Solution 3 |

