diff --git a/docs/sources/k6/next/javascript-api/k6-browser/page/_index.md b/docs/sources/k6/next/javascript-api/k6-browser/page/_index.md index b552c38aa7..6f06c02a18 100644 --- a/docs/sources/k6/next/javascript-api/k6-browser/page/_index.md +++ b/docs/sources/k6/next/javascript-api/k6-browser/page/_index.md @@ -10,6 +10,8 @@ Page provides methods to interact with a single tab in a running web browser. A | Method | Description | | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [$(selector)](https://grafana.com/docs/k6//javascript-api/k6-browser/page/page-dollar) | Finds an element matching the specified `selector` within the page. | +| [$$(selector)](https://grafana.com/docs/k6//javascript-api/k6-browser/page/page-doubledollar) | Finds all elements matching the specified `selector` within the page. | | [bringToFront()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/bringtofront) | Activates a browser tab. | | [check(selector[, options])](https://grafana.com/docs/k6//javascript-api/k6-browser/page/check/) | Select the input checkbox. | | [click(selector[, options])](https://grafana.com/docs/k6//javascript-api/k6-browser/page/click/) | Clicks on an element matching a `selector`. | @@ -18,8 +20,6 @@ Page provides methods to interact with a single tab in a running web browser. A | [context()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/context) | Gets the [BrowserContext](https://grafana.com/docs/k6//javascript-api/k6-browser/browsercontext) that the page belongs to. | | [dblclick(selector[, options])](https://grafana.com/docs/k6//javascript-api/k6-browser/page/dblclick/) | With the [Mouse](https://grafana.com/docs/k6//javascript-api/k6-browser/mouse), double click on an element matching the provided `selector`. | | [dispatchEvent(selector, type, eventInit[, options])](https://grafana.com/docs/k6//javascript-api/k6-browser/page/dispatchevent/) | Dispatches HTML DOM event types e.g. `'click'` | -| [page$(selector)](https://grafana.com/docs/k6//javascript-api/k6-browser/page/page-dollar) | Finds an element matching the specified `selector` within the page. | -| [page$$(selector)](https://grafana.com/docs/k6//javascript-api/k6-browser/page/page-doubledollar) | Finds all elements matching the specified `selector` within the page. | | [emulateMedia([options])](https://grafana.com/docs/k6//javascript-api/k6-browser/page/emulatemedia/) | Changes the CSS media type and the color scheme feature. | | [emulateVisionDeficiency(type)](https://grafana.com/docs/k6//javascript-api/k6-browser/page/emulatevisiondeficiency) | Emulates your website with the specified vision deficiency `type`. | | [evaluate(pageFunction[, arg])](https://grafana.com/docs/k6//javascript-api/k6-browser/page/evaluate/) | Returns the value of the `pageFunction` invocation. | @@ -28,6 +28,13 @@ Page provides methods to interact with a single tab in a running web browser. A | [focus(selector[, options])](https://grafana.com/docs/k6//javascript-api/k6-browser/page/focus/) | Fetches an element with `selector` and focuses on it. | | [frames()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/frames) | Returns an array of frames on the page. | | [getAttribute(selector, name[, options])](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getattribute/) | Returns the element attribute value for the given attribute name. | +| [getByAltText(altText[, options])](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbyalttext/) | Returns a locator for elements with the specified `alt` attribute text. | +| [getByLabel(text[, options])](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbylabel/) | Returns a locator for form controls with the specified label text. | +| [getByPlaceholder(placeholder[, options])](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbyplaceholder/) | Returns a locator for input elements with the specified `placeholder` attribute text. | +| [getByRole(role[, options])](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbyrole/) | Returns a locator for elements with the specified ARIA role. | +| [getByTestId(testId)](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbytestid/) | Returns a locator for elements with the specified `data-testid` attribute. | +| [getByText(text[, options])](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbytext/) | Returns a locator for elements containing the specified text. | +| [getByTitle(title[, options])](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbytitle/) | Returns a locator for elements with the specified `title` attribute. | | [goto(url[, options])](https://grafana.com/docs/k6//javascript-api/k6-browser/page/goto/) | Navigates to the specified `url`. | | [hover(selector[, options])](https://grafana.com/docs/k6//javascript-api/k6-browser/page/hover/) | Hovers over an element matching `selector`. | | [innerHTML(selector[, options])](https://grafana.com/docs/k6//javascript-api/k6-browser/page/innerhtml/) | Returns the `element.innerHTML`. | diff --git a/docs/sources/k6/next/javascript-api/k6-browser/page/getbyalttext.md b/docs/sources/k6/next/javascript-api/k6-browser/page/getbyalttext.md new file mode 100644 index 0000000000..99de7ff3ff --- /dev/null +++ b/docs/sources/k6/next/javascript-api/k6-browser/page/getbyalttext.md @@ -0,0 +1,183 @@ +--- +title: 'getByAltText(altText[, options])' +description: 'Browser module: page.getByAltText(altText[, options]) method' +--- + +# getByAltText(altText[, options]) + +Returns a locator for elements with the specified alt text. This method is useful for locating images and other elements that have an `alt` attribute, making your tests more accessible and user-focused. + + + +| Parameter | Type | Default | Description | +| ------------- | -------------- | ------- | ---------------------------------------------------------------------------------------------------------- | +| altText | string\|RegExp | - | Required. The alt text to search for. Can be a string for exact match or a RegExp for pattern matching. | +| options | object | `null` | | +| options.exact | boolean | `false` | Whether to match the alt text exactly with case sensitivity. When `true`, performs a case-sensitive match. | + + + +### Returns + +| Type | Description | +| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| [Locator](https://grafana.com/docs/k6//javascript-api/k6-browser/locator/) | A locator object that can be used to interact with the element(s) matching the specified alt text. | + +### Examples + +#### Basic alt text matching + +Find and click an image by its alt text: + + + +```javascript +import { browser } from 'k6/browser'; + +export const options = { + scenarios: { + ui: { + executor: 'shared-iterations', + options: { + browser: { + type: 'chromium', + }, + }, + }, + }, +}; + +export default async function () { + const page = await browser.newPage(); + + try { + await page.goto('https://quickpizza.grafana.com'); + + const logo = page.getByAltText('LOGO'); + await logo.waitFor(); + + await logo.click(); + await page.waitForLoadState(); + } finally { + await page.close(); + } +} +``` + +#### Exact alt text matching + +Use exact matching for precise alt text: + + + +```javascript +import { browser } from 'k6/browser'; + +export const options = { + scenarios: { + ui: { + executor: 'shared-iterations', + options: { + browser: { + type: 'chromium', + }, + }, + }, + }, +}; + +export default async function () { + const page = await browser.newPage(); + + try { + await page.goto('https://quickpizza.grafana.com'); + + const logo = page.getByAltText('logo', { exact: true }); + await logo.waitFor(); + + await logo.click(); + await page.waitForLoadState(); + } finally { + await page.close(); + } +} +``` + +#### Using regular expressions + +Find images using pattern matching: + + + +```javascript +import { browser } from 'k6/browser'; + +export const options = { + scenarios: { + ui: { + executor: 'shared-iterations', + options: { + browser: { + type: 'chromium', + }, + }, + }, + }, +}; + +export default async function () { + const page = await browser.newPage(); + + try { + await page.goto('https://quickpizza.grafana.com'); + + const logo = page.getByAltText(/logo/s); + await logo.waitFor(); + + await logo.click(); + await page.waitForLoadState(); + } finally { + await page.close(); + } +} +``` + +### Common use cases + +**Image testing:** + +- Testing image alt text for accessibility compliance +- Interacting with clickable images/banners + +**Accessibility testing:** + +- Ensuring all images have meaningful alt text +- Testing screen reader compatibility +- Validating WCAG compliance + +**UI interaction:** + +- Clicking on logo images to navigate home +- Selecting images in galleries or carousels +- Interacting with image-based buttons + +### Best practices + +1. **Use descriptive alt text**: When creating tests, ensure your application uses meaningful alt text that describes the image content or function. + +2. **Prefer exact matches**: Use `exact: true` when you need precise matching to avoid false positives. + +3. **Accessibility-first**: Using `getByAltText()` encourages better accessibility practices by ensuring images have proper alt attributes. + +4. **Regular expressions for patterns**: Use RegExp for flexible matching when dealing with dynamic or numbered content. + +5. **Combine with assertions**: Always verify that the located elements behave as expected using assertions. + +### Related + +- [page.getByRole()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbyrole/) - Locate by ARIA role +- [page.getByLabel()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbylabel/) - Locate by form labels +- [page.getByPlaceholder()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbyplaceholder/) - Locate by placeholder text +- [page.getByTestId()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbytestid/) - Locate by test ID +- [page.getByTitle()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbytitle/) - Locate by title attribute +- [page.getByText()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbytext/) - Locate by visible text diff --git a/docs/sources/k6/next/javascript-api/k6-browser/page/getbylabel.md b/docs/sources/k6/next/javascript-api/k6-browser/page/getbylabel.md new file mode 100644 index 0000000000..acae9b3f79 --- /dev/null +++ b/docs/sources/k6/next/javascript-api/k6-browser/page/getbylabel.md @@ -0,0 +1,191 @@ +--- +title: 'getByLabel(text[, options])' +description: 'Browser module: page.getByLabel(text[, options]) method' +--- + +# getByLabel(text[, options]) + +Returns a locator for form controls associated with the specified label text. This method is ideal for interacting with form elements in an accessible and user-focused way, as it mirrors how users typically identify form fields. + + + +| Parameter | Type | Default | Description | +| ------------- | -------------- | ------- | ------------------------------------------------------------------------------------------------------------ | +| text | string\|RegExp | - | Required. The label text to search for. Can be a string for exact match or a RegExp for pattern matching. | +| options | object | `null` | | +| options.exact | boolean | `false` | Whether to match the label text exactly with case sensitivity. When `true`, performs a case-sensitive match. | + + + +### Returns + +| Type | Description | +| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | +| [Locator](https://grafana.com/docs/k6//javascript-api/k6-browser/locator/) | A locator object that can be used to interact with the form control associated with the specified label. | + +### Examples + +#### Basic form interaction + +Fill form fields using their labels: + + + +```javascript +import { browser } from 'k6/browser'; + +export const options = { + scenarios: { + ui: { + executor: 'shared-iterations', + options: { + browser: { + type: 'chromium', + }, + }, + }, + }, +}; + +export default async function () { + const page = await browser.newPage(); + + try { + await page.setContent(` + + + + + `); + + const username = page.getByLabel('Username (hint: default)', { exact: true }); + const password = page.getByLabel(/^Password.*$/); + + await username.fill('default'); + await password.fill('12345678'); + } finally { + await page.close(); + } +} +``` + +#### Working with different input types + +Handle various form control types in various label association patterns: + + + +```javascript +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.setContent(` + + + Password (hint: 12345678) + + + + + + + + + + + `); + + // Inputs + page.getByLabel('Username (hint: default)', { exact: true }).fill('default'); + page.getByLabel(/^Password.*$/).fill('12345678'); + + // Checkbox + await page.getByLabel('Subscribe to newsletter').check(); + + // Radio button + await page.getByLabel('Email', { exact: true }).check(); + + // Select dropdown + await page.getByLabel('Theme').selectOption('light'); + + // Textarea + await page.getByLabel('Comments').fill('This is a test comment'); + } finally { + await page.close(); + } +} +``` + +### Label association patterns + +The `getByLabel()` method works with several HTML patterns for associating labels with form controls: + +**1. Explicit association with `for` attribute:** + + + +```html + +``` + +**2. ARIA labeling:** + + + +```html +Username +``` + +**3. ARIA label attribute:** + + + +```html + +``` + +### Common use cases + +- **Form testing**: Login forms, registration forms, contact forms +- **E-commerce**: Checkout forms, shipping information, payment details +- **Settings pages**: User preferences, account settings, configuration forms +- **Accessibility testing**: Ensuring proper label association and screen reader compatibility + +### Best practices + +1. **Accessibility-first approach**: Using `getByLabel()` ensures your tests work the same way users with assistive technology interact with forms. + +2. **Meaningful labels**: Encourage developers to use descriptive, unique label text that clearly identifies the form control's purpose. + +3. **Required field indicators**: When testing required fields, include any visual indicators (like asterisks) in your label text matching. + +4. **Form validation testing**: Use labels to test form validation scenarios, as they provide a stable way to identify fields regardless of styling changes. + +### Related + +- [page.getByRole()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbyrole/) - Locate by ARIA role +- [page.getByAltText()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbyalttext/) - Locate by alt text +- [page.getByPlaceholder()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbyplaceholder/) - Locate by placeholder text +- [page.getByTestId()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbytestid/) - Locate by test ID +- [page.getByTitle()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbytitle/) - Locate by title attribute +- [page.getByText()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbytext/) - Locate by text content diff --git a/docs/sources/k6/next/javascript-api/k6-browser/page/getbyplaceholder.md b/docs/sources/k6/next/javascript-api/k6-browser/page/getbyplaceholder.md new file mode 100644 index 0000000000..a019e87807 --- /dev/null +++ b/docs/sources/k6/next/javascript-api/k6-browser/page/getbyplaceholder.md @@ -0,0 +1,112 @@ +--- +title: 'getByPlaceholder(placeholder[, options])' +description: 'Browser module: page.getByPlaceholder(placeholder[, options]) method' +--- + +# getByPlaceholder(placeholder[, options]) + +Returns a locator for input elements with the specified `placeholder` attribute. This method is useful for locating form fields that use `placeholder` attribute to provide hints or examples to users about the expected input format. + + + +| Parameter | Type | Default | Description | +| ------------- | -------------- | ------- | ------------------------------------------------------------------------------------------------------------------ | +| placeholder | string\|RegExp | - | Required. The placeholder text to search for. Can be a string for exact match or a RegExp for pattern matching. | +| options | object | `null` | | +| options.exact | boolean | `false` | Whether to match the placeholder text exactly with case sensitivity. When `true`, performs a case-sensitive match. | + + + +### Returns + +| Type | Description | +| -------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| [Locator](https://grafana.com/docs/k6//javascript-api/k6-browser/locator/) | A locator object that can be used to interact with the input element(s) matching the specified placeholder text. | + +### Examples + +Find and fill inputs by their placeholder text: + + + +```javascript +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.setContent(` + + + + + + `); + + await page.getByPlaceholder('First name').fill('First'); + await page.getByPlaceholder('Last name').fill('Last'); + await page.getByPlaceholder('dd/mm/yyyy').fill('01/01/1990'); + + await page.getByPlaceholder('your.email@example.com').fill('first.last@example.com'); + await page.getByPlaceholder('+1 (555) 123-4567').fill('+1 (555) 987-6543'); + } finally { + await page.close(); + } +} +``` + +### Common use cases + +**Form field identification:** + +- Login and registration forms without explicit labels +- Quick search boxes +- Filter and input controls +- Comment and feedback forms + +**E-commerce:** + +- Product search bars +- Quantity input fields +- Promo code entry +- Address and payment information + +**Interactive applications:** + +- Chat input fields +- Command input interfaces +- Settings and configuration forms +- Data entry applications + +### Best practices + +1. **Complement, don't replace labels**: Placeholder text should supplement, not replace proper form labels for accessibility. + +2. **Use descriptive placeholders**: Ensure placeholder text clearly indicates the expected input format or content. + +3. **Consider internationalization**: When testing multi-language applications, be aware that placeholder text may change. + +4. **Accessibility considerations**: Remember that placeholder text alone may not be sufficient for users with disabilities. + +### Related + +- [page.getByRole()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbyrole/) - Locate by ARIA role +- [page.getByAltText()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbyalttext/) - Locate by alt text +- [page.getByLabel()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbylabel/) - Locate by form labels (preferred for accessibility) +- [page.getByTestId()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbytestid/) - Locate by test ID +- [page.getByTitle()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbytitle/) - Locate by title attribute +- [page.getByText()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbytext/) - Locate by visible text diff --git a/docs/sources/k6/next/javascript-api/k6-browser/page/getbyrole.md b/docs/sources/k6/next/javascript-api/k6-browser/page/getbyrole.md new file mode 100644 index 0000000000..11e152395f --- /dev/null +++ b/docs/sources/k6/next/javascript-api/k6-browser/page/getbyrole.md @@ -0,0 +1,227 @@ +--- +title: 'getByRole(role[, options])' +description: 'Browser module: page.getByRole(role[, options]) method' +--- + +# 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. + + + +| Parameter | Type | Default | Description | +| --------------------- | -------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------- | +| role | string | - | Required. The ARIA role to search for (e.g. `'button'`, `'link'`, `'heading'`, `'textbox'`, etc.). | +| options | object | `null` | | +| options.checked | boolean | `null` | Filter elements by their checked state. Only applicable for roles like `checkbox`, `radio`, `menuitemcheckbox`. | +| options.disabled | boolean | `null` | Filter elements by their disabled state. | +| options.exact | boolean | `false` | Whether to match the accessible name exactly with case sensitivity. When `true`, performs a case-sensitive match. | +| options.expanded | boolean | `null` | Filter elements by their expanded state. Only applicable for roles that support the `aria-expanded` attribute. | +| options.includeHidden | boolean | `false` | Whether to include elements that are normally excluded from the accessibility tree in the search. | +| options.level | number | `null` | Filter headings by their level 1 to 6. Only applicable for `heading` role. | +| options.name | string\|RegExp | `null` | Filter elements by their accessible name. The accessible name is typically the text content, label text, or aria-label attribute. | +| options.pressed | boolean | `null` | Filter elements by their pressed state. Only applicable for roles like `button` with toggle behavior. | +| options.selected | boolean | `null` | Filter elements by their selected state. Only applicable for roles like `option`, `tab`. | + + + +### Returns + +| Type | Description | +| -------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | +| [Locator](https://grafana.com/docs/k6//javascript-api/k6-browser/locator/) | A locator object that can be used to interact with the element(s) matching the specified role and options. | + +### Examples + +#### Basic role selection + +Find and click a button by its role: + + + +```javascript +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 elements +- `checkbox` - Checkable boxes that can be on/off +- `combobox` - Editable dropdown combining input and listbox +- `listbox` - Container for selectable list options +- `menu` - Menu of actions or navigation +- `menubar` - Container for top-level menus +- `menuitem` - Option within a menu +- `menuitemcheckbox` - Checkable menu item +- `menuitemradio` - Mutually exclusive menu item +- `meter` - Scalar measurement within a known range +- `option` - Selectable option in a listbox or combobox +- `progressbar` - Progress indicator of an operation +- `radio` - Single-select option in a group +- `radiogroup` - Grouping of related radio buttons +- `scrollbar` - Control for scrolling content +- `searchbox` - Text field for search input +- `separator` - Divider that separates content or controls +- `slider` - Adjustable value control within a range +- `spinbutton` - Numeric input with increment/decrement controls +- `status` - Advisory status information (non-alert) +- `switch` - On/off toggle control +- `tab` - A tab in a tabbed interface +- `tablist` - Container for a set of tabs +- `tabpanel` - Content panel associated with a tab +- `textbox` - Input field for free-form text +- `timer` - Running time display that updates +- `toolbar` - Group of interactive controls +- `tooltip` - Contextual help popup +- `tree` - Hierarchical list of items +- `treeitem` - Item in a tree + +#### Tables & Grids + +- `table` - Tabular data with rows and columns +- `rowgroup` - Section that groups rows (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 (like 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 source +- `caption` - Caption for a figure, table, or media +- `code` - Fragment of computer code +- `definition` - Definition of a term +- `deletion` - Content removed from a document +- `directory` - List of references +- `document` - Standalone document content +- `emphasis` - Content with emphatic stress +- `feed` - Stream of articles or entries +- `figure` - Figure with optional caption +- `generic` - Generic container with no specific semantics +- `img` - Image treated as a single graphic +- `insertion` - Content added to a document +- `link` - Hyperlink to another location +- `list` - List of items +- `listitem` - A single item within a list +- `mark` - Highlighted or marked content +- `marquee` - Scrolling region of text +- `math` - Mathematical expression +- `note` - An aside or annotation +- `none` - No semantic role; remove semantics +- `paragraph` - Paragraph of text +- `presentation` - Presentational only; ignore semantics +- `strong` - Content of strong importance +- `subscript` - Subscripted text +- `superscript` - Superscripted text +- `term` - A term being defined +- `time` - A time or date + +#### Landmarks & Regions + +- `banner` - Site header landmark +- `complementary` - Complementary content (sidebar) +- `contentinfo` - Page footer information +- `form` - Region containing a form +- `main` - Main content landmark +- `navigation` - Navigation region of links +- `region` - Generic region of the page +- `search` - Search region +- `application` - Application container widget + +#### Usage Examples by Category + +**Form Testing:** + + + + +```javascript +// 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:** + + + + +```javascript +// Tabs +await page.getByRole('tab', { name: 'Overview' }).click(); +await expect(page.getByRole('tabpanel', { name: 'Overview' })).toBeVisible(); +``` + +**Content Verification:** + + + + +```javascript +// 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 + +1. **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. + +2. **Use accessible names**: Always try to use the `name` option to make your tests more specific and reliable. + +3. **Consider accessibility**: Using `getByRole()` encourages better accessibility practices in your application by ensuring elements have proper ARIA roles. + +### Related + +- [page.getByAltText()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbyalttext/) - Locate by alt text +- [page.getByLabel()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbylabel/) - Locate by form labels +- [page.getByPlaceholder()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbyplaceholder/) - Locate by placeholder text +- [page.getByTestId()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbytestid/) - Locate by test ID +- [page.getByText()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbytext/) - Locate by text content +- [page.getByTitle()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbytitle/) - Locate by title attribute diff --git a/docs/sources/k6/next/javascript-api/k6-browser/page/getbytestid.md b/docs/sources/k6/next/javascript-api/k6-browser/page/getbytestid.md new file mode 100644 index 0000000000..a26991be2f --- /dev/null +++ b/docs/sources/k6/next/javascript-api/k6-browser/page/getbytestid.md @@ -0,0 +1,86 @@ +--- +title: 'getByTestId(testId)' +description: 'Browser module: page.getByTestId(testId) method' +--- + +# getByTestId(testId) + +Returns a locator for elements with the specified test ID attribute. This method is designed for robust test automation by locating elements using dedicated test identifiers that are independent of the visual appearance or content changes. Currently it can only work with the `data-testid` attribute. + + + +| Parameter | Type | Default | Description | +| --------- | -------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | +| testId | string\|RegExp | - | Required. The test ID value to search for. Searches for the `data-testid` attribute. Can be a string for exact match or a RegExp for pattern matching. | + + + +### Returns + +| Type | Description | +| -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| [Locator](https://grafana.com/docs/k6//javascript-api/k6-browser/locator/) | A locator object that can be used to interact with the element(s) matching the specified test ID. | + +### Examples + +#### Basic test ID usage + +Locate and interact with elements using test IDs: + + + +```javascript +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.setContent(` + + + + `); + + await page.getByTestId('username').fill('FirstLast'); + await page.getByTestId('email').fill('firstlast@example.com'); + await page.getByTestId('submit-button').click(); + } finally { + await page.close(); + } +} +``` + +### Best practices + +1. **Stable identifiers**: Use meaningful, stable test IDs that won't change with refactoring or content updates. + +2. **Hierarchical naming**: Use consistent naming conventions like `user-profile-edit-btn`. + +3. **Avoid duplicates**: Ensure test IDs are unique within the page to prevent ambiguity. + +4. **Strategic placement**: Add test IDs to key interactive elements and components that are frequently tested. + +5. **Team coordination**: Establish test ID conventions with your development team to ensure consistency. + +### Related + +- [page.getByRole()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbyrole/) - Locate by ARIA role +- [page.getByAltText()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbyalttext/) - Locate by alt text +- [page.getByLabel()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbylabel/) - Locate by form labels +- [page.getByPlaceholder()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbyplaceholder/) - Locate by placeholder text +- [page.getByText()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbytext/) - Locate by text content +- [page.getByTitle()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbytitle/) - Locate by title attribute diff --git a/docs/sources/k6/next/javascript-api/k6-browser/page/getbytext.md b/docs/sources/k6/next/javascript-api/k6-browser/page/getbytext.md new file mode 100644 index 0000000000..b2917e15a5 --- /dev/null +++ b/docs/sources/k6/next/javascript-api/k6-browser/page/getbytext.md @@ -0,0 +1,129 @@ +--- +title: 'getByText(text[, options])' +description: 'Browser module: page.getByText(text[, options]) method' +--- + +# getByText(text[, options]) + +Returns a locator for elements containing the specified text. This method finds elements by their visible text content, making it ideal for locating user-facing content like buttons, links, headings, and other text elements. + + + +| Parameter | Type | Default | Description | +| ------------- | -------------- | ------- | ----------------------------------------------------------------------------------------------------------- | +| text | string\|RegExp | - | Required. The text content to search for. Can be a string for exact match or a RegExp for pattern matching. | +| options | object | `null` | | +| options.exact | boolean | `false` | Whether to match the text exactly with case sensitivity. When `true`, performs a case-sensitive match. | + + + +### Returns + +| Type | Description | +| -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | +| [Locator](https://grafana.com/docs/k6//javascript-api/k6-browser/locator/) | A locator object that can be used to interact with the element(s) containing the specified text. | + +### Examples + +Find and click elements by their visible text: + + + +```javascript +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.getByText('Pizza, Please!').click(); + + const noThanksBtn = page.getByText('No thanks'); + await noThanksBtn.click(); + } finally { + await page.close(); + } +} +``` + +### Text matching behavior + +**Whitespace normalization**: Text matching automatically normalizes whitespace, meaning: + +- Multiple spaces become single spaces +- Line breaks become spaces +- Leading and trailing whitespace is ignored + +Consider the following DOM structure: + + + + +```html +
Hello world
+
Hello
+``` + +You can locate by text substring, exact string, or a regular expression: + + + + +```js +// Matches +page.getByText('world'); +// Matches first
+page.getByText('Hello world'); +// Matches second
+page.getByText('Hello', { exact: true }); +// Matches both
s +page.getByText(/Hello/); +// Matches second
+page.getByText(/^hello$/i); +``` + +### Common use cases + +- **Button interactions**: Submit, Cancel, Delete, Edit buttons +- **Navigation**: Menu items, breadcrumbs, pagination links +- **Content verification**: Success messages, error messages, headings +- **Form interactions**: Checkbox labels, radio button options +- **Status indicators**: Active, Inactive, Pending states + +### Best practices + +1. **User-focused testing**: Using `getByText()` ensures your tests interact with content as users see it. + +2. **Avoid brittle text**: Be cautious with exact text that might change frequently (like dates, counts, or user-generated content). + +3. **Use meaningful text**: Prefer descriptive button text and labels over generic terms like "Click here" or "Button". + +4. **Handle dynamic content**: Use regular expressions for text that contains variable parts (timestamps, user names, counts). + +5. **Consider accessibility**: Text-based selection encourages better accessibility practices in your application. + +6. **Internationalization**: For multi-language applications, consider using test IDs or roles instead of text for critical interactions. + +### Related + +- [page.getByRole()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbyrole/) - Locate by ARIA role +- [page.getByAltText()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbyalttext/) - Locate by alt text +- [page.getByLabel()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbylabel/) - Locate by form labels +- [page.getByPlaceholder()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbyplaceholder/) - Locate by placeholder text +- [page.getByTestId()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbytestid/) - Locate by test ID +- [page.getByTitle()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbytitle/) - Locate by title attribute diff --git a/docs/sources/k6/next/javascript-api/k6-browser/page/getbytitle.md b/docs/sources/k6/next/javascript-api/k6-browser/page/getbytitle.md new file mode 100644 index 0000000000..ed4cd987d1 --- /dev/null +++ b/docs/sources/k6/next/javascript-api/k6-browser/page/getbytitle.md @@ -0,0 +1,118 @@ +--- +title: 'getByTitle(title[, options])' +description: 'Browser module: page.getByTitle(title[, options]) method' +--- + +# getByTitle(title[, options]) + +Returns a locator for elements with the specified `title` attribute. This method is useful for locating elements that use the `title` attribute to provide additional information, tooltips, or accessibility context. + + + +| Parameter | Type | Default | Description | +| ------------- | -------------- | ------- | ------------------------------------------------------------------------------------------------------------ | +| title | string\|RegExp | - | Required. The title text to search for. Can be a string for exact match or a RegExp for pattern matching. | +| options | object | `null` | | +| options.exact | boolean | `false` | Whether to match the title text exactly with case sensitivity. When `true`, performs a case-sensitive match. | + + + +### Returns + +| Type | Description | +| -------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | +| [Locator](https://grafana.com/docs/k6//javascript-api/k6-browser/locator/) | A locator object that can be used to interact with the element(s) matching the specified title attribute. | + +### Examples + +Find and interact with elements by their title attribute: + + + +```javascript +import { browser } from 'k6/browser'; +import { expect } from 'https://jslib.k6.io/k6-testing/0.5.0/index.js'; + +export const options = { + scenarios: { + browser: { + executor: 'shared-iterations', + options: { + browser: { + type: 'chromium', + }, + }, + }, + }, +}; + +export default async function () { + const page = await browser.newPage(); + + try { + await page.setContent(` + + + + `); + + await page.getByTitle('Hello World').click(); + + await page.getByTitle('Favorite Color').selectOption('Red'); + + await page.getByTitle('Check me').check(); + } finally { + await page.close(); + } +} +``` + +### Common use cases + +**User interface controls:** + +- Toolbar buttons and action items +- Navigation controls (previous/next, pagination) +- Media player controls +- Menu and dropdown triggers + +**Informational elements:** + +- Help icons and tooltips +- Status indicators and badges +- Progress indicators +- Warning and error messages + +**Accessibility support:** + +- Screen reader descriptions +- Alternative text for complex elements +- Context-sensitive help +- Form field explanations + +### Best practices + +1. **Meaningful titles**: Ensure title attributes provide clear, helpful information about the element's purpose or content. + +2. **Accessibility compliance**: Use titles to enhance accessibility, especially for elements that might not have clear visual labels. + +3. **Avoid redundancy**: Don't duplicate visible text in the title attribute unless providing additional context. + +4. **Dynamic content**: When testing applications with changing title content, use flexible matching patterns or regular expressions. + +5. **Tooltip testing**: Remember that title attributes often create tooltips on hover, which can be useful for UI testing. + +6. **Internationalization**: Consider that title text may change in different language versions of your application. + +### Related + +- [page.getByRole()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbyrole/) - Locate by ARIA role +- [page.getByAltText()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbyalttext/) - Locate by alt text +- [page.getByLabel()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbylabel/) - Locate by form labels +- [page.getByPlaceholder()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbyplaceholder/) - Locate by placeholder text +- [page.getByTestId()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbytestid/) - Locate by test ID +- [page.getByText()](https://grafana.com/docs/k6//javascript-api/k6-browser/page/getbytext/) - Locate by visible text