How does React Testing Library's guiding principle influence query choice?
This tests whether you prioritize user-visible attributes over implementation details when selecting queries. A strong answer ranks getByRole, label, and text above testId because users interact with meaning, not data attributes.
WHAT THIS TESTS: The interviewer wants to know if you understand that React Testing Library is built around user-centric testing rather than testing implementation details. They are checking whether you treat tests as a simulation of real user behavior and whether you know the official query priority order that reflects this philosophy.
A GOOD ANSWER COVERS: First, state the principle plainly: tests should interact with the DOM the way a real user would. Second, explain the query priority hierarchy. Priority one is getByRole because it mirrors how assistive technology and users perceive interactive elements like buttons and links. Priority two is getByLabelText for form fields because users associate inputs with their labels. Priority three is getByText for non-interactive elements. Priority four is getByTestId, which should be a last resort because data-testid is invisible to users. Third, mention that this approach catches accessibility issues for free because getByRole enforces proper ARIA roles and accessible names. Fourth, note that this reduces test brittleness since text and roles change less often than CSS classes or DOM structure.
COMMON WRONG ANSWERS: Reaching for getByTestId or querySelector for everything is a major red flag because it ignores the guiding principle entirely. Insisting that querying by class name or id is acceptable shows you are still thinking in implementation details rather than user behavior. Another weak pattern is saying you use data attributes for stability without acknowledging that you are sacrificing user fidelity. A subtle mistake is claiming getByRole is only for accessibility testing rather than the default query for interactive elements.
LIKELY FOLLOW-UPS: The interviewer may ask what you do when getByRole returns multiple matches and how you narrow queries without resorting to testId. They might ask how you test elements that have no visible text or accessible name. They could also ask how this principle applies to user events, such as preferring userEvent over fireEvent because userEvent mimics realistic interaction sequences.
ONE CONCRETE EXAMPLE: Imagine a submit button styled with a class of btn-primary. A poor test queries by class name. A strong test uses screen.getByRole('button', { name: /submit/i }) because a real user looks for a button labeled Submit, not a CSS class. If the design system changes the class to btn-cta, the strong test still passes, while the class-based test breaks even though user behavior is unchanged.
Read the original → testing-library.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.