How Should I Query?

Priority

Based on the Guiding Principles, your test should resemble how users interact with your code (component, page, etc.) as much as possible. With this in mind, we recommend this order of priority:

  1. Queries Accessible to Everyone queries that reflect the experience of visual users as well as those that use assistive technology
    • getByText: This is the number 1 method a user finds any visible text on interactive and non-interactive elements.
    • getByDisplayValue: Useful for the current value of a TextInput.
    • getByPlaceholderText: Only useful for targeting a placeholder of a TextInput.
    • getByLabelText: This can be used to query every element that is exposed in the accessibility tree as a label, usually when there's no visible text.
    • getByHintText: This can be used to query every element that is exposed in the accessibility tree as a hint. Make sure it also has a label set.
    • getByAccessibilityState: This can be used to query every element that is exposed in the accessibility tree as a state of an interactive element, like a checkbox.
    • getByAccessibilityValue: This can be used to query every element that is exposed in the accessibility tree as a value on a range, like a slider.
  2. Queries Users Can Infer
    • getByRole: This can be used to query every element that is exposed in the accessibility tree as a role, like buttons or images.
  3. Test IDs
    • getByTestId: The user cannot see (or hear) these, so this is only recommended for cases where you can't match by text or it doesn't make sense