QA Graphic

Get By Selector Cheat Sheet

A handy reference guide for Playwright's "Get By" selectors using TypeScript.

About This Cheat Sheet

When working with Playwright in TypeScript, selecting elements efficiently is key to writing robust automation scripts. Playwright provides a variety of "Get By" methods to locate elements based on different attributes, text, roles, and more. This cheat sheet summarizes the most commonly used methods, making it a quick reference for developers and testers alike.

Below is the code from the cheat sheet, formatted for easy reading. Feel free to copy and use it in your projects.

Code Breakdown

const element = await page.getByText('Click me');
const input = await page.getByLabel('Username');
const input = await page.getByPlaceholder('Enter your name');
const image = await page.getByAlt('Product Image');
const link = await page.getByTitle('Learn More');
const button = await page.getByRole('button');
const component = await page.getByTestId('product-card');
const nav = await page.getByAriaLabel('Main Navigation');

How to Use These Selectors

  • getByText: Selects an element containing the specified text.
  • getByLabel: Targets input elements by their associated label text.
  • getByPlaceholder: Finds input elements by their placeholder text.
  • getByAlt: Selects image elements by their alt text.
  • getByTitle: Targets elements with a specific title attribute.
  • getByRole: Selects elements by their ARIA role for better accessibility.
  • getByTestId: Finds elements by a custom data-testid attribute, often used in testing.
  • getByAriaLabel: Targets elements by their ARIA label for accessibility-focused testing.

Keep this cheat sheet handy as you build your Playwright scripts. Download the image above to have it as a quick reference whenever you need it.

 

Comments

Add Your Comments