getByRole(role[, options])
Returns a locator for elements with the specified ARIA role. This is the preferred way to locate elements as it most closely resembles how users and assistive technology perceive the page.
Returns
Examples
Basic role selection
Find and click a button by its role:
import { browser } from 'k6/browser';
export const options = {
scenarios: {
browser: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
};
export default async function () {
const page = await browser.newPage();
try {
await page.goto('https://quickpizza.grafana.com/');
await page.getByRole('button', { name: 'Pizza, Please!' }).click();
} finally {
page.close();
}
}
Complete ARIA roles reference
The following roles are supported and can be used with getByRole()
, organized by category:
Widgets & Inputs
button
- Buttons and clickable elementscheckbox
- Checkable boxes that can be on/offcombobox
- Editable drop-down menu combining input and list boxlistbox
- Container for selectable list optionsmenu
- Menu of actions or navigationmenubar
- Container for top-level menusmenuitem
- Option within a menumenuitemcheckbox
- Checkable menu itemmenuitemradio
- Mutually exclusive menu itemmeter
- Scalar measurement within a known rangeoption
- Selectable option in a list box or combo boxprogressbar
- Progress indicator of an operationradio
- Single-select option in a groupradiogroup
- Grouping of related radio buttonsscrollbar
- Control for scrolling contentsearchbox
- Text field for search inputseparator
- Divider that separates content or controlsslider
- Adjustable value control within a rangespinbutton
- Numeric input with increment/decrement controlsstatus
- Advisory status information (non-alert)switch
- On/off toggle controltab
- A tab in a tabbed interfacetablist
- Container for a set of tabstabpanel
- Content panel associated with a tabtextbox
- Input field for free-form texttimer
- Running time display that updatestoolbar
- Group of interactive controlstooltip
- Contextual help popuptree
- Hierarchical list of itemstreeitem
- Item in a tree
Tables & Grids
table
- Tabular data with rows and columns.rowgroup
- Section that groups rows. For example,thead
,tbody
,tfoot
.row
- A row of cells within a table or grid.rowheader
- Header cell for a row.columnheader
- Header cell for a column.cell
- Data cell in a table.grid
- Interactive, tabular widget, such as a spreadsheet.gridcell
- Cell within a grid.treegrid
- Tree-structured grid with expandable rows.
Document Structure & Semantics
article
- Self-contained composition (article)blockquote
- Quotation from another sourcecaption
- Caption for a figure, table, or mediacode
- Fragment of computer codedefinition
- Definition of a termdeletion
- Content removed from a documentdirectory
- List of referencesdocument
- Standalone document contentemphasis
- Content with emphatic stressfeed
- Stream of articles or entriesfigure
- Figure with optional captiongeneric
- Generic container with no specific semanticsimg
- Image treated as a single graphicinsertion
- Content added to a documentlink
- Hyperlink to another locationlist
- List of itemslistitem
- A single item within a listmark
- Highlighted or marked contentmarquee
- Scrolling region of textmath
- Mathematical expressionnote
- An aside or annotationnone
- No semantic role; remove semanticsparagraph
- Paragraph of textpresentation
- Presentational only; ignore semanticsstrong
- Content of strong importancesubscript
- Subscripted textsuperscript
- Superscripted textterm
- A term being definedtime
- A time or date
Landmarks & Regions
banner
- Site header landmarkcomplementary
- Complementary content (sidebar)contentinfo
- Page footer informationform
- Region containing a formmain
- Main content landmarknavigation
- Navigation region of linksregion
- Generic region of the pagesearch
- Search regionapplication
- Application container widget
Usage Examples by Category
- Form Testing:
// Text inputs
await page.getByRole('textbox', { name: 'Email' }).fill('user@example.com');
await page.getByRole('searchbox', { name: 'Search products' }).fill('laptop');
// Selections
await page.getByRole('checkbox', { name: 'Agree to terms' }).check();
await page.getByRole('radio', { name: 'Standard shipping' }).check();
await page.getByRole('combobox', { name: 'Country' }).selectOption('US');
// Interactive controls
await page.getByRole('slider', { name: 'Volume' }).fill('75');
await page.getByRole('switch', { name: 'Enable notifications' }).click();
- Navigation Testing:
// Tabs
await page.getByRole('tab', { name: 'Overview' }).click();
await expect(page.getByRole('tabpanel', { name: 'Overview' })).toBeVisible();
- Content Verification:
// Structure
await expect(page.getByRole('article')).toHaveCount(5);
await expect(page.getByRole('heading', { level: 1 })).toHaveText('Welcome');
// Status and feedback
await expect(page.getByRole('alert')).toHaveText('Form submitted successfully');
await expect(page.getByRole('status')).toHaveText('3 items selected');
Best practices
- Prefer role-based selection:
getByRole()
is the preferred method for locating elements as it closely mirrors how users and assistive technology interact with your page. - Use accessible names: Always try to use the
name
option to make your tests more specific and reliable. - Consider accessibility: Using
getByRole()
encourages better accessibility practices in your application by ensuring elements have proper ARIA roles.
Related
- page.getByAltText() - Locate by alt text
- page.getByLabel() - Locate by form labels
- page.getByPlaceholder() - Locate by placeholder text
- page.getByTestId() - Locate by test ID
- page.getByText() - Locate by text content
- page.getByTitle() - Locate by title attribute