Chapter 2 of 4

Queries

Finding elements the way a user would, in priority order.

Testing Library offers many queries, and the order you should prefer them in is deliberate: the higher up the list, the closer it is to how a real user finds things.

  1. getByRole - the way assistive technology sees the page. Almost always the right choice.
  2. getByLabelText - for form fields, and it verifies the label is correctly associated.
  3. getByPlaceholderText - when there is genuinely no label.
  4. getByText - for non-interactive content.
  5. getByDisplayValue, getByAltText, getByTitle - narrower cases.
  6. getByTestId - the escape hatch, when nothing else identifies the element.
screen.getByRole("button", { name: /save changes/i });
screen.getByRole("heading", { level: 1 });
screen.getByRole("textbox", { name: /email/i });
screen.getByLabelText(/password/i);
screen.getByText(/no results found/i);

get, query and find

  • getBy... - throws if not found. Use when the element should be there.
  • queryBy... - returns null if not found. The only one to use for asserting absence.
  • findBy... - returns a promise and retries. Use for anything that appears asynchronously.
// Present
expect(screen.getByRole("alert")).toBeInTheDocument();

// Absent - getBy would throw before the assertion ran
expect(screen.queryByRole("alert")).not.toBeInTheDocument();

// Appears later
expect(await screen.findByText(/welcome back/i)).toBeInTheDocument();

The All variants

expect(screen.getAllByRole("listitem")).toHaveLength(3);