Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readTestingReact

Pick the right Testing Library query

Use accessible roles and names to query React components and diagnose a mismatch from Testing Library's error.

A test that clicks getByTestId('save-btn') can pass after someone replaces a real button with a clickable div. Query by role and accessible name to catch that change. Test keyboard behavior separately.

// @vitest-environment jsdom
import React from 'react'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { expect, test, vi } from 'vitest'

function ProfileForm({ onSave }) {
  return (
    <form onSubmit={(event) => {
      event.preventDefault()
      onSave()
    }}>
      <label htmlFor="name">Display name</label>
      <input id="name" defaultValue="Sadat" />
      <button data-testid="save-btn" type="submit">Save changes</button>
    </form>
  )
}

test('saves the profile', async () => {
  const user = userEvent.setup()
  const onSave = vi.fn()
  render(<ProfileForm onSave={onSave} />)

  await user.click(screen.getByRole('button', { name: /save/i }))

  expect(onSave).toHaveBeenCalledTimes(1)
  expect(screen.getByLabelText('Display name').value).toBe('Sadat')
})

Run this test in jsdom. ProfileForm renders a labelled input and a <button> that says "Save changes", and this test passes. getByRole finds the button by its role and its accessible name, which here is the text inside it. getByLabelText finds the input by its label.

Query what a user can find

Testing Library documents a priority order for queries. It starts with role and ends with the test id.

  1. getByRole, with the name option
  2. getByLabelText
  3. getByPlaceholderText
  4. getByText
  5. getByDisplayValue
  6. getByAltText
  7. getByTitle
  8. getByTestId

The first five queries use information people encounter in the interface. A test ID uses a separate attribute. Here /save/i accepts both Save and Save changes. Use an exact accessible name if the wording matters.

Read the failure

Change the pattern to /submit/i to see the roles and names Testing Library found in the query container.

The error includes this role listing.

TestingLibraryElementError: Unable to find an accessible element with the role "button" and name `/submit/i`

Here are the accessible roles:

  textbox:

  Name "Display name":
  <input id="name" value="Sadat" />

  button:

  Name "Save changes":
  <button data-testid="save-btn" type="submit" />

The message shows a button named "Save changes" and a textbox named "Display name". You see the pattern is wrong before you open the component.

What a test id lets through

The same label can be a div with a click handler and a test id.

export function DivSave({ onSave }) {
  return (
    <div data-testid="save-btn" onClick={onSave}>
      Save changes
    </div>
  )
}

getByTestId('save-btn') finds it and passes. getByRole('button', { name: /save/i }) fails for this fixture because the div has no button role. It also has no keyboard interaction.

Start with getByRole and move down the list when the query cannot describe the element. For example, password inputs have no implicit role, so query them by label.