😅 Totally understand the frustration — it feels like overkill to check two things separately when all you want is “find the element with both a label and a data-testid.” Unfortunately, Testing Library is very opinionated about querying "like a user" — labels, roles, etc. — and doesn't officially support combining queries like getByLabelText + getByTestId.
But! There are some ways to make this easier or cleaner 🔧
✅ Cleaner Way: Write a Utility Function
You can write a custom matcher or utility to abstract the dual query:
getByLabelTextAndTestId.js
import { screen } from '@testing-library/react';
/**
* Find an element by label text and test ID
*/
export function getByLabelTextAndTestId(labelText, testId) {
const elByLabel = screen.getByLabelText(labelText);
const elByTestId = screen.getByTestId(testId);
if (elByLabel !== elByTestId) {
throw new Error(
`No single element matches both label="${labelText}" and data-testid="${testId}"`
);
}
return elByLabel;
}
Usage:
test('gets the correct input', () => {
render(
<>
<label htmlFor="email">Email</label>
<input id="email" data-testid="email-input" />
</>
);
const input = getByLabelTextAndTestId('Email', 'email-input');
expect(input).toBeInTheDocument();
});
✅ Now you can DRY it up and still fail with a useful error when things go wrong.
⚙️ Even Fancier: Custom Query (Advanced 🔍)
If you love DRYness and want a pure selector-based query, you could build your own with within:
import { queryHelpers, buildQueries } from '@testing-library/react';
const queryAllByLabelAndTestId = (container, label, testId) => {
const labelEls = queryHelpers.queryAllByLabelText(container, label);
return labelEls.filter((el) =>
el.getAttribute('data-testid') === testId
);
};
const [
queryByLabelAndTestId,
getAllByLabelAndTestId,
getByLabelAndTestId,
findAllByLabelAndTestId,
findByLabelAndTestId
] = buildQueries(queryAllByLabelAndTestId, (c, l, id) => `Multiple elements found for label="${l}" and data-testid="${id}"`, (c, l, id) => `No element found for label="${l}" and data-testid="${id}"`);
export {
getByLabelAndTestId,
getAllByLabelAndTestId,
findByLabelAndTestId,
findAllByLabelAndTestId
};
Hello, custom query power ⚡️
Let me know how you want to balance cleanliness vs. Testing Library dogma — I can help shape it to your preferences!