πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Questions
Question 59 of 100
Locators
Intermediate

When would you use getByRole() over getByText()?

The Answer

Use `getByRole()` for interactive elements (buttons, links, inputs, checkboxes) because it filters hidden elements and is semantically correct. Use `getByText()` for asserting visible static content (paragraphs, headings, labels).

Deep Dive Explanation

The key rule: if a user INTERACTS with it (clicks, types), use `getByRole`. If you just want to VERIFY text is visible on screen, use `getByText`. The role-based approach also aligns with accessibility standards β€” if `getByRole` can't find your button, a screen reader user can't either.

example.spec.ts
// Interactive elements β†’ getByRole (PREFERRED)
await page.getByRole('button', { name: 'Sign In' }).click();
await page.getByRole('link', { name: 'Privacy Policy' }).click();
await page.getByRole('textbox', { name: 'Email' }).fill('user@example.com');

// Static content β†’ getByText
await expect(page.getByText('Your order has been placed')).toBeVisible();
await expect(page.getByText('Welcome, John!')).toBeVisible();

// Heading β†’ getByRole with level
await expect(page.getByRole('heading', { name: 'Dashboard', level: 1 })).toBeVisible();