Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

feat(locator): page-free `by` locators resolved with page.get() (#42157)

Pavel Feldman7eae07322944
diff --git a/docs/src/api/class-by.md b/docs/src/api/class-by.md
new file mode 100644
index 0000000000..6e3831443f
--- /dev/null
+++ b/docs/src/api/class-by.md
@@ -0,0 +1,254 @@
+# class: By
+* since: v1.63
+* langs: js
+
+[By] describes an element without being bound to a [Page] or a [Frame]. It is built with the
+top-level [`property: Playwright.by`] object and turned into a regular [Locator] with
+[`method: Page.get`], [`method: Frame.get`] or [`method: Locator.get`].
+
+Since a [By] carries no page, it can be defined once at module scope and reused by every test,
+which makes it a natural fit for page objects.
+
+**Usage**
+
+```js
+import { by, expect, test } from '@playwright/test';
+
+const saveButton = by.role('button', { name: 'Save' });
+const todoItems = by.testId('todo-list').role('listitem');
+
+test('saves a todo', async ({ page }) => {
+ await page.get(saveButton).click();
+ await expect(page.get(todoItems)).toHaveCount(1);
+});
+```
+
+A [By] chain resolves to the same element as the matching [Locator] chain, so
+`page.get(by.testId('list').text('Row'))` and `page.getByTestId('list').getByText('Row')` are
+interchangeable. Chaining composes rather than replaces: `page.get(outer.get(inner))` and
+`page.get(outer).get(inner)` describe the same element.
+
+## method: By.altText
+* since: v1.63
+- returns: <[By]>
+
+Matches a descendant element by its `alt` text.
+
+### param: By.altText.text = %%-locator-get-by-text-text-%%
+* since: v1.63
+
+### option: By.altText.exact = %%-locator-get-by-text-exact-%%
+* since: v1.63
+
+## method: By.and
+* since: v1.63
+- returns: <[By]>
+
+Narrows down the match to elements that match both this and the given [By].
+
+**Usage**
+
+```js
+const saveButton = by.role('button').and(by.title('Subscribe'));
+```
+
+### param: By.and.by
+* since: v1.63
+- `by` <[By]>
+
+Additional locator to match.
+
+## method: By.describe
+* since: v1.63
+- returns: <[By]>
+
+Describes the element, the description is used in the trace viewer and the reports.
+
+### param: By.describe.description
+* since: v1.63
+- `description` <[string]>
+
+Locator description.
+
+## method: By.filter
+* since: v1.63
+- returns: <[By]>
+
+Narrows down the match according to the options, for example filters by text. It can be chained to
+filter multiple times.
+
+**Usage**
+
+```js
+const rowWithButton = by.get('tr')
+ .filter({ hasText: 'text in column 1' })
+ .filter({ has: by.role('button', { name: 'column 2 button' }) });
+```
+
+### option: By.filter.has
+* since: v1.63
+- `has` <[By]>
+
+Narrows down the results to those which contain elements matching this relative [By]. The inner
+[By] is queried starting with the outer match, not the document root.
+
+### option: By.filter.hasNot
+* since: v1.63
+- `hasNot` <[By]>
+
+Matches elements that do not contain an element matching this relative [By]. The inner [By] is
+queried starting with the outer match, not the document root.
+
+### option: By.filter.hasNotText = %%-locator-option-has-not-text-%%
+* since: v1.63
+
+### option: By.filter.hasText = %%-locator-option-has-text-%%
+* since: v1.63
+
+### option: By.filter.visible = %%-locator-option-visible-%%
+* since: v1.63
+
+## method: By.first
+* since: v1.63
+- returns: <[By]>
+
+Matches the first matching element.
+
+## method: By.get
+* since: v1.63
+- returns: <[By]>
+
+Matches a descendant element by a selector or by another [By].
+
+**Usage**
+
+```js
+const firstCell = by.get('table').get('td').first();
+
+const listItem = by.role('listitem');
+const unread = by.testId('inbox').get(listItem).filter({ hasText: 'Unread' });
+```
+
+**Details**
+
+Passing a [By] composes rather than replaces, so `outer.get(inner.get(innermost))` and
+`outer.get(inner).get(innermost)` describe the same element.
+
+### param: By.get.selectorOrBy
+* since: v1.63
+- `selectorOrBy` <[string]|[By]>
+
+A selector or a [By] to match inside this one.
+
+## method: By.label
+* since: v1.63
+- returns: <[By]>
+
+Matches an input element by the text of the associated `<label>` or `aria-label` attribute.
+
+### param: By.label.text = %%-locator-get-by-text-text-%%
+* since: v1.63
+
+### option: By.label.exact = %%-locator-get-by-text-exact-%%
+* since: v1.63
+
+## method: By.last
+* since: v1.63
+- returns: <[By]>
+
+Matches the last matching element.
+
+## method: By.nth
+* since: v1.63
+- returns: <[By]>
+
+Matches the n-th matching element. It is zero based, `nth(0)` selects the first element.
+
+### param: By.nth.index
+* since: v1.63
+- `index` <[int]>
+
+## method: By.or
+* since: v1.63
+- returns: <[By]>
+
+Matches elements matching either this or the given [By].
+
+**Usage**
+
+```js
+const dialogOrButton = by.role('dialog').or(by.role('button'));
+```
+
+### param: By.or.by
+* since: v1.63
+- `by` <[By]>
+
+Alternative locator to match.
+
+## method: By.placeholder
+* since: v1.63
+- returns: <[By]>
+
+Matches an input element by the placeholder text.
+
+### param: By.placeholder.text = %%-locator-get-by-text-text-%%
+* since: v1.63
+
+### option: By.placeholder.exact = %%-locator-get-by-text-exact-%%
+* since: v1.63
+
+## method: By.role
+* since: v1.63
+- returns: <[By]>
+
+Matches an element by its [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
+[ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
+[accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
+
+### param: By.role.role = %%-get-by-role-to-have-role-role-%%
+* since: v1.63
+
+### option: By.role.-inline- = %%-locator-get-by-role-option-list-v1.27-%%
+* since: v1.63
+
+### option: By.role.description = %%-locator-get-by-role-option-description-%%
+* since: v1.63
+
+### option: By.role.exact = %%-locator-get-by-role-option-exact-%%
+* since: v1.63
+
+## method: By.testId
+* since: v1.63
+- returns: <[By]>
+
+Matches an element by the test id. The test id attribute is resolved when the [By] is bound to a
+page, so a [By] built at module scope still honours
+[`method: Selectors.setTestIdAttribute`] and the `testIdAttribute` option.
+
+### param: By.testId.testId = %%-locator-get-by-test-id-test-id-%%
+* since: v1.63
+
+## method: By.text
+* since: v1.63
+- returns: <[By]>
+
+Matches an element containing the given text.
+
+### param: By.text.text = %%-locator-get-by-text-text-%%
+* since: v1.63
+
+### option: By.text.exact = %%-locator-get-by-text-exact-%%
+* since: v1.63
+
+## method: By.title
+* since: v1.63
+- returns: <[By]>
+
+Matches an element by its `title` attribute.
+
+### param: By.title.text = %%-locator-get-by-text-text-%%
+* since: v1.63
+
+### option: By.title.exact = %%-locator-get-by-text-exact-%%
+* since: v1.63
diff --git a/docs/src/api/class-frame.md b/docs/src/api/class-frame.md
index 56db47d57f..35fcd345ab 100644
--- a/docs/src/api/class-frame.md
+++ b/docs/src/api/class-frame.md
@@ -1002,6 +1002,19 @@ await locator.ClickAsync();
### param: Frame.frameLocator.selector = %%-find-selector-%%
* since: v1.17
+## method: Frame.get
+* since: v1.63
+* langs: js
+- returns: <[Locator]>
+
+%%-template-locator-get-%%
+
+### param: Frame.get.by
+* since: v1.63
+- `by` <[By]>
+
+Page-free locator built with [`property: Playwright.by`].
+
## async method: Frame.getAttribute
* since: v1.8
* discouraged: Use locator-based [`method: Locator.getAttribute`] instead. Read more about [locators](../locators.md).
diff --git a/docs/src/api/class-framelocator.md b/docs/src/api/class-framelocator.md
index 7f19ceb465..287d652452 100644
--- a/docs/src/api/class-framelocator.md
+++ b/docs/src/api/class-framelocator.md
@@ -98,6 +98,19 @@ in that iframe.
### param: FrameLocator.frameLocator.selector = %%-find-selector-%%
* since: v1.17
+## method: FrameLocator.get
+* since: v1.63
+* langs: js
+- returns: <[Locator]>
+
+%%-template-locator-get-%%
+
+### param: FrameLocator.get.by
+* since: v1.63
+- `by` <[By]>
+
+Page-free locator built with [`property: Playwright.by`].
+
## method: FrameLocator.getByAltText
* since: v1.27
- returns: <[Locator]>
diff --git a/docs/src/api/class-locator.md b/docs/src/api/class-locator.md
index 46dcf7c955..a428e2938e 100644
--- a/docs/src/api/class-locator.md
+++ b/docs/src/api/class-locator.md
@@ -1479,6 +1479,19 @@ await locator.ClickAsync();
### param: Locator.frameLocator.selector = %%-find-selector-%%
* since: v1.17
+## method: Locator.get
+* since: v1.63
+* langs: js
+- returns: <[Locator]>
+
+%%-template-locator-get-%%
+
+### param: Locator.get.by
+* since: v1.63
+- `by` <[By]>
+
+Page-free locator built with [`property: Playwright.by`].
+
## async method: Locator.getAttribute
* since: v1.14
- returns: <[null]|[string]>
diff --git a/docs/src/api/class-page.md b/docs/src/api/class-page.md
index 9cb83bef41..179a2b3b9a 100644
--- a/docs/src/api/class-page.md
+++ b/docs/src/api/class-page.md
@@ -2252,6 +2252,19 @@ await locator.ClickAsync();
An array of all frames attached to the page.
+## method: Page.get
+* since: v1.63
+* langs: js
+- returns: <[Locator]>
+
+%%-template-locator-get-%%
+
+### param: Page.get.by
+* since: v1.63
+- `by` <[By]>
+
+Page-free locator built with [`property: Playwright.by`].
+
## async method: Page.getAttribute
* since: v1.8
* discouraged: Use locator-based [`method: Locator.getAttribute`] instead. Read more about [locators](../locators.md).
diff --git a/docs/src/api/class-playwright.md b/docs/src/api/class-playwright.md
index e0579eabc8..15e1049675 100644
--- a/docs/src/api/class-playwright.md
+++ b/docs/src/api/class-playwright.md
@@ -84,6 +84,24 @@ class PlaywrightExample
}
```
+## property: Playwright.by
+* since: v1.63
+* langs: js
+- type: <[By]>
+
+Builds page-free locators that are resolved with [`method: Page.get`], [`method: Frame.get`] or
+[`method: Locator.get`]. See [By] for details.
+
+```js
+import { by, test } from '@playwright/test';
+
+const saveButton = by.role('button', { name: 'Save' });
+
+test('saves', async ({ page }) => {
+ await page.get(saveButton).click();
+});
+```
+
## property: Playwright.chromium
* since: v1.8
- type: <[BrowserType]>
diff --git a/docs/src/api/params.md b/docs/src/api/params.md
index 9a812dc0e5..4ed1a68f08 100644
--- a/docs/src/api/params.md
+++ b/docs/src/api/params.md
@@ -1537,6 +1537,38 @@ Locator is resolved to the element immediately before performing an action, so a
[Learn more about locators](../locators.md).
+## template-locator-get
+
+Binds a page-free [By] locator, returning a [Locator] scoped to this object.
+
+**Usage**
+
+Consider a page object that describes elements without a page:
+
+```js
+// todo-page.ts
+import { by } from '@playwright/test';
+
+export const newTodo = by.placeholder('What needs to be done?');
+export const todoItems = by.testId('todo-list').role('listitem');
+```
+
+```js
+import { expect, test } from '@playwright/test';
+import { newTodo, todoItems } from './todo-page';
+
+test('adds a todo', async ({ page }) => {
+ await page.get(newTodo).fill('buy milk');
+ await expect(page.get(todoItems)).toHaveCount(1);
+});
+```
+
+**Details**
+
+The resolved [Locator] is the same one the equivalent `getBy*` chain would produce, so
+`page.get(by.testId('list').text('Row'))` and `page.getByTestId('list').getByText('Row')` match the
+same element.
+
## template-locator-get-by-test-id
Locate element by the test id.
diff --git a/docs/src/locators.md b/docs/src/locators.md
index 3a6a5de389..8c15177a20 100644
--- a/docs/src/locators.md
+++ b/docs/src/locators.md
@@ -1778,6 +1778,47 @@ await page.GetByRole(AriaRole.Button).CountAsync();
You can explicitly opt-out from strictness check by telling Playwright which element to use when multiple elements match, through [`method: Locator.first`], [`method: Locator.last`], and [`method: Locator.nth`]. These methods are **not recommended** because when your page changes, Playwright may click on an element you did not intend. Instead, follow best practices above to create a locator that uniquely identifies the target element.
+## Page-free locators
+* langs: js
+
+A [Locator] is bound to a page, so it can only be created once a page exists. [By] describes the
+same element without a page, which means it can be defined once at module scope and shared between
+tests. Build one with the top-level `by` object and bind it with [`method: Page.get`],
+[`method: Frame.get`] or [`method: Locator.get`].
+
+```js
+// todo-page.ts
+import { by } from '@playwright/test';
+
+export const newTodo = by.placeholder('What needs to be done?');
+export const todoItems = by.testId('todo-list').role('listitem');
+```
+
+```js
+import { expect, test } from '@playwright/test';
+import { newTodo, todoItems } from './todo-page';
+
+test('adds a todo', async ({ page }) => {
+ await page.get(newTodo).fill('buy milk');
+ await page.get(newTodo).press('Enter');
+ await expect(page.get(todoItems)).toHaveCount(1);
+});
+```
+
+A [By] supports the same chaining, filtering and operators as a [Locator], and resolves to exactly
+the same element, so `page.get(by.testId('list').text('Row'))` and
+`page.getByTestId('list').getByText('Row')` are interchangeable. Since a [By] is immutable, scoping
+one never changes the original:
+
+```js
+const list = by.testId('todo-list');
+const first = list.role('listitem').first();
+const active = list.filter({ has: by.get('.active') });
+```
+
+Test ids are resolved when the [By] is bound to a page, so a module-scope [By] still honours the
+`testIdAttribute` option from the config.
+
## More Locators
For less commonly used locators, look at the [other locators](./other-locators.md) guide.
diff --git a/packages/isomorphic/by.ts b/packages/isomorphic/by.ts
new file mode 100644
index 0000000000..a34116b01b
--- /dev/null
+++ b/packages/isomorphic/by.ts
@@ -0,0 +1,145 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { getByAltTextSelector, getByLabelSelector, getByPlaceholderSelector, getByRoleSelector, getByTestIdSelector, getByTextSelector, getByTitleSelector } from './locatorUtils';
+import { escapeForTextSelector } from './stringUtils';
+
+import type { ByRoleOptions } from './locatorUtils';
+
+export type ByFilterOptions = {
+ has?: By;
+ hasNot?: By;
+ hasNotText?: string | RegExp;
+ hasText?: string | RegExp;
+ visible?: boolean;
+};
+
+export interface By {
+ altText(text: string | RegExp, options?: { exact?: boolean }): By;
+ and(by: By): By;
+ describe(description: string): By;
+ filter(options?: ByFilterOptions): By;
+ first(): By;
+ get(selectorOrBy: string | By): By;
+ label(text: string | RegExp, options?: { exact?: boolean }): By;
+ last(): By;
+ nth(index: number): By;
+ or(by: By): By;
+ placeholder(text: string | RegExp, options?: { exact?: boolean }): By;
+ role(role: string, options?: ByRoleOptions): By;
+ testId(testId: string | RegExp): By;
+ text(text: string | RegExp, options?: { exact?: boolean }): By;
+ title(text: string | RegExp, options?: { exact?: boolean }): By;
+}
+
+type SelectorBuilder = (testIdAttributeName: string) => string;
+
+class ByImpl implements By {
+ readonly _build: SelectorBuilder;
+
+ constructor(build: SelectorBuilder) {
+ this._build = build;
+ }
+
+ private _append(build: SelectorBuilder): ByImpl {
+ return new ByImpl(testIdAttributeName => {
+ const parent = this._build(testIdAttributeName);
+ const child = build(testIdAttributeName);
+ return parent ? `${parent} >> ${child}` : child;
+ });
+ }
+
+ altText(text: string | RegExp, options?: { exact?: boolean }): By {
+ return this._append(() => getByAltTextSelector(text, options));
+ }
+
+ and(by: By): By {
+ return this._append(name => `internal:and=` + JSON.stringify(resolveBy(by, name)));
+ }
+
+ describe(description: string): By {
+ return this._append(() => `internal:describe=` + JSON.stringify(description));
+ }
+
+ filter(options?: ByFilterOptions): By {
+ let result: ByImpl = this;
+ if (options?.hasText)
+ result = result._append(() => `internal:has-text=${escapeForTextSelector(options.hasText!, false)}`);
+ if (options?.hasNotText)
+ result = result._append(() => `internal:has-not-text=${escapeForTextSelector(options.hasNotText!, false)}`);
+ if (options?.has)
+ result = result._append(name => `internal:has=` + JSON.stringify(resolveBy(options.has!, name)));
+ if (options?.hasNot)
+ result = result._append(name => `internal:has-not=` + JSON.stringify(resolveBy(options.hasNot!, name)));
+ if (options?.visible !== undefined)
+ result = result._append(() => `visible=${options.visible ? 'true' : 'false'}`);
+ return result;
+ }
+
+ first(): By {
+ return this.nth(0);
+ }
+
+ get(selectorOrBy: string | By): By {
+ return this._append(name => typeof selectorOrBy === 'string' ? selectorOrBy : resolveBy(selectorOrBy, name));
+ }
+
+ label(text: string | RegExp, options?: { exact?: boolean }): By {
+ return this._append(() => getByLabelSelector(text, options));
+ }
+
+ last(): By {
+ return this.nth(-1);
+ }
+
+ nth(index: number): By {
+ return this._append(() => `nth=${index}`);
+ }
+
+ or(by: By): By {
+ return this._append(name => `internal:or=` + JSON.stringify(resolveBy(by, name)));
+ }
+
+ placeholder(text: string | RegExp, options?: { exact?: boolean }): By {
+ return this._append(() => getByPlaceholderSelector(text, options));
+ }
+
+ role(role: string, options?: ByRoleOptions): By {
+ return this._append(() => getByRoleSelector(role, options));
+ }
+
+ testId(testId: string | RegExp): By {
+ return this._append(name => getByTestIdSelector(name, testId));
+ }
+
+ text(text: string | RegExp, options?: { exact?: boolean }): By {
+ return this._append(() => getByTextSelector(text, options));
+ }
+
+ title(text: string | RegExp, options?: { exact?: boolean }): By {
+ return this._append(() => getByTitleSelector(text, options));
+ }
+}
+
+export const by: By = new ByImpl(() => '');
+
+// The test id attribute is only known once the By is bound to a page, hence the deferred build.
+export function resolveBy(by: By, testIdAttributeName: string): string {
+ const selector = (by as ByImpl)._build(testIdAttributeName);
+ if (!selector)
+ throw new Error(`Empty "by" locator. Start with one of by.role(), by.text(), by.testId() and friends.`);
+ return selector;
+}
diff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.ts
index 48f2fb9293..97bf61e5a1 100644
--- a/packages/playwright-client/types/types.d.ts
+++ b/packages/playwright-client/types/types.d.ts
@@ -3011,6 +3011,41 @@ export interface Page {
*/
frames(): Array<Frame>;
+ /**
+ * Binds a page-free [By](https://playwright.dev/docs/api/class-by) locator, returning a
+ * [Locator](https://playwright.dev/docs/api/class-locator) scoped to this object.
+ *
+ * **Usage**
+ *
+ * Consider a page object that describes elements without a page:
+ *
+ * ```js
+ * // todo-page.ts
+ * import { by } from '@playwright/test';
+ *
+ * export const newTodo = by.placeholder('What needs to be done?');
+ * export const todoItems = by.testId('todo-list').role('listitem');
+ * ```
+ *
+ * ```js
+ * import { expect, test } from '@playwright/test';
+ * import { newTodo, todoItems } from './todo-page';
+ *
+ * test('adds a todo', async ({ page }) => {
+ * await page.get(newTodo).fill('buy milk');
+ * await expect(page.get(todoItems)).toHaveCount(1);
+ * });
+ * ```
+ *
+ * **Details**
+ *
+ * The resolved [Locator](https://playwright.dev/docs/api/class-locator) is the same one the equivalent `getBy*` chain
+ * would produce, so `page.get(by.testId('list').text('Row'))` and `page.getByTestId('list').getByText('Row')` match
+ * the same element.
+ * @param by Page-free locator built with [playwright.by](https://playwright.dev/docs/api/class-playwright#playwright-by).
+ */
+ get(by: By): Locator;
+
/**
* **NOTE** Use locator-based
* [locator.getAttribute(name[, options])](https://playwright.dev/docs/api/class-locator#locator-get-attribute)
@@ -7361,6 +7396,41 @@ export interface Frame {
*/
frameLocator(selector: string): FrameLocator;
+ /**
+ * Binds a page-free [By](https://playwright.dev/docs/api/class-by) locator, returning a
+ * [Locator](https://playwright.dev/docs/api/class-locator) scoped to this object.
+ *
+ * **Usage**
+ *
+ * Consider a page object that describes elements without a page:
+ *
+ * ```js
+ * // todo-page.ts
+ * import { by } from '@playwright/test';
+ *
+ * export const newTodo = by.placeholder('What needs to be done?');
+ * export const todoItems = by.testId('todo-list').role('listitem');
+ * ```
+ *
+ * ```js
+ * import { expect, test } from '@playwright/test';
+ * import { newTodo, todoItems } from './todo-page';
+ *
+ * test('adds a todo', async ({ page }) => {
+ * await page.get(newTodo).fill('buy milk');
+ * await expect(page.get(todoItems)).toHaveCount(1);
+ * });
+ * ```
+ *
+ * **Details**
+ *
+ * The resolved [Locator](https://playwright.dev/docs/api/class-locator) is the same one the equivalent `getBy*` chain
+ * would produce, so `page.get(by.testId('list').text('Row'))` and `page.getByTestId('list').getByText('Row')` match
+ * the same element.
+ * @param by Page-free locator built with [playwright.by](https://playwright.dev/docs/api/class-playwright#playwright-by).
+ */
+ get(by: By): Locator;
+
/**
* **NOTE** Use locator-based
* [locator.getAttribute(name[, options])](https://playwright.dev/docs/api/class-locator#locator-get-attribute)
@@ -15437,6 +15507,41 @@ export interface Locator {
*/
frameLocator(selector: string): FrameLocator;
+ /**
+ * Binds a page-free [By](https://playwright.dev/docs/api/class-by) locator, returning a
+ * [Locator](https://playwright.dev/docs/api/class-locator) scoped to this object.
+ *
+ * **Usage**
+ *
+ * Consider a page object that describes elements without a page:
+ *
+ * ```js
+ * // todo-page.ts
+ * import { by } from '@playwright/test';
+ *
+ * export const newTodo = by.placeholder('What needs to be done?');
+ * export const todoItems = by.testId('todo-list').role('listitem');
+ * ```
+ *
+ * ```js
+ * import { expect, test } from '@playwright/test';
+ * import { newTodo, todoItems } from './todo-page';
+ *
+ * test('adds a todo', async ({ page }) => {
+ * await page.get(newTodo).fill('buy milk');
+ * await expect(page.get(todoItems)).toHaveCount(1);
+ * });
+ * ```
+ *
+ * **Details**
+ *
+ * The resolved [Locator](https://playwright.dev/docs/api/class-locator) is the same one the equivalent `getBy*` chain
+ * would produce, so `page.get(by.testId('list').text('Row'))` and `page.getByTestId('list').getByText('Row')` match
+ * the same element.
+ * @param by Page-free locator built with [playwright.by](https://playwright.dev/docs/api/class-playwright#playwright-by).
+ */
+ get(by: By): Locator;
+
/**
* Returns the matching element's attribute value.
*
@@ -20438,6 +20543,319 @@ export interface BrowserServer {
[Symbol.asyncDispose](): Promise<void>;
}
+/**
+ * [By](https://playwright.dev/docs/api/class-by) describes an element without being bound to a
+ * [Page](https://playwright.dev/docs/api/class-page) or a [Frame](https://playwright.dev/docs/api/class-frame). It is
+ * built with the top-level [playwright.by](https://playwright.dev/docs/api/class-playwright#playwright-by) object and
+ * turned into a regular [Locator](https://playwright.dev/docs/api/class-locator) with
+ * [page.get(by)](https://playwright.dev/docs/api/class-page#page-get),
+ * [frame.get(by)](https://playwright.dev/docs/api/class-frame#frame-get) or
+ * [locator.get(by)](https://playwright.dev/docs/api/class-locator#locator-get).
+ *
+ * Since a [By](https://playwright.dev/docs/api/class-by) carries no page, it can be defined once at module scope and
+ * reused by every test, which makes it a natural fit for page objects.
+ *
+ * **Usage**
+ *
+ * ```js
+ * import { by, expect, test } from '@playwright/test';
+ *
+ * const saveButton = by.role('button', { name: 'Save' });
+ * const todoItems = by.testId('todo-list').role('listitem');
+ *
+ * test('saves a todo', async ({ page }) => {
+ * await page.get(saveButton).click();
+ * await expect(page.get(todoItems)).toHaveCount(1);
+ * });
+ * ```
+ *
+ * A [By](https://playwright.dev/docs/api/class-by) chain resolves to the same element as the matching
+ * [Locator](https://playwright.dev/docs/api/class-locator) chain, so `page.get(by.testId('list').text('Row'))` and
+ * `page.getByTestId('list').getByText('Row')` are interchangeable. Chaining composes rather than replaces:
+ * `page.get(outer.get(inner))` and `page.get(outer).get(inner)` describe the same element.
+ */
+export interface By {
+ /**
+ * Matches a descendant element by its `alt` text.
+ * @param text Text to locate the element for.
+ * @param options
+ */
+ altText(text: string|RegExp, options?: {
+ /**
+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
+ * regular expression. Note that exact match still trims whitespace.
+ */
+ exact?: boolean;
+ }): By;
+
+ /**
+ * Narrows down the match to elements that match both this and the given
+ * [By](https://playwright.dev/docs/api/class-by).
+ *
+ * **Usage**
+ *
+ * ```js
+ * const saveButton = by.role('button').and(by.title('Subscribe'));
+ * ```
+ *
+ * @param by Additional locator to match.
+ */
+ and(by: By): By;
+
+ /**
+ * Describes the element, the description is used in the trace viewer and the reports.
+ * @param description Locator description.
+ */
+ describe(description: string): By;
+
+ /**
+ * Narrows down the match according to the options, for example filters by text. It can be chained to filter multiple
+ * times.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const rowWithButton = by.get('tr')
+ * .filter({ hasText: 'text in column 1' })
+ * .filter({ has: by.role('button', { name: 'column 2 button' }) });
+ * ```
+ *
+ * @param options
+ */
+ filter(options?: {
+ /**
+ * Narrows down the results to those which contain elements matching this relative
+ * [By](https://playwright.dev/docs/api/class-by). The inner [By](https://playwright.dev/docs/api/class-by) is queried
+ * starting with the outer match, not the document root.
+ */
+ has?: By;
+
+ /**
+ * Matches elements that do not contain an element matching this relative
+ * [By](https://playwright.dev/docs/api/class-by). The inner [By](https://playwright.dev/docs/api/class-by) is queried
+ * starting with the outer match, not the document root.
+ */
+ hasNot?: By;
+
+ /**
+ * Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
+ * When passed a [string], matching is case-insensitive and searches for a substring.
+ */
+ hasNotText?: string|RegExp;
+
+ /**
+ * Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
+ * passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
+ * `<article><div>Playwright</div></article>`.
+ */
+ hasText?: string|RegExp;
+
+ /**
+ * Only matches visible or invisible elements.
+ */
+ visible?: boolean;
+ }): By;
+
+ /**
+ * Matches the first matching element.
+ */
+ first(): By;
+
+ /**
+ * Matches a descendant element by a selector or by another [By](https://playwright.dev/docs/api/class-by).
+ *
+ * **Usage**
+ *
+ * ```js
+ * const firstCell = by.get('table').get('td').first();
+ *
+ * const listItem = by.role('listitem');
+ * const unread = by.testId('inbox').get(listItem).filter({ hasText: 'Unread' });
+ * ```
+ *
+ * **Details**
+ *
+ * Passing a [By](https://playwright.dev/docs/api/class-by) composes rather than replaces, so
+ * `outer.get(inner.get(innermost))` and `outer.get(inner).get(innermost)` describe the same element.
+ * @param selectorOrBy A selector or a [By](https://playwright.dev/docs/api/class-by) to match inside this one.
+ */
+ get(selectorOrBy: string|By): By;
+
+ /**
+ * Matches an input element by the text of the associated `<label>` or `aria-label` attribute.
+ * @param text Text to locate the element for.
+ * @param options
+ */
+ label(text: string|RegExp, options?: {
+ /**
+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
+ * regular expression. Note that exact match still trims whitespace.
+ */
+ exact?: boolean;
+ }): By;
+
+ /**
+ * Matches the last matching element.
+ */
+ last(): By;
+
+ /**
+ * Matches the n-th matching element. It is zero based, `nth(0)` selects the first element.
+ * @param index
+ */
+ nth(index: number): By;
+
+ /**
+ * Matches elements matching either this or the given [By](https://playwright.dev/docs/api/class-by).
+ *
+ * **Usage**
+ *
+ * ```js
+ * const dialogOrButton = by.role('dialog').or(by.role('button'));
+ * ```
+ *
+ * @param by Alternative locator to match.
+ */
+ or(by: By): By;
+
+ /**
+ * Matches an input element by the placeholder text.
+ * @param text Text to locate the element for.
+ * @param options
+ */
+ placeholder(text: string|RegExp, options?: {
+ /**
+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
+ * regular expression. Note that exact match still trims whitespace.
+ */
+ exact?: boolean;
+ }): By;
+
+ /**
+ * Matches an element by its [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
+ * [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
+ * [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
+ * @param role Required aria role.
+ * @param options
+ */
+ role(role: "alert"|"alertdialog"|"application"|"article"|"banner"|"blockquote"|"button"|"caption"|"cell"|"checkbox"|"code"|"columnheader"|"combobox"|"complementary"|"contentinfo"|"definition"|"deletion"|"dialog"|"directory"|"document"|"emphasis"|"feed"|"figure"|"form"|"generic"|"grid"|"gridcell"|"group"|"heading"|"img"|"insertion"|"link"|"list"|"listbox"|"listitem"|"log"|"main"|"marquee"|"math"|"meter"|"menu"|"menubar"|"menuitem"|"menuitemcheckbox"|"menuitemradio"|"navigation"|"none"|"note"|"option"|"paragraph"|"presentation"|"progressbar"|"radio"|"radiogroup"|"region"|"row"|"rowgroup"|"rowheader"|"scrollbar"|"search"|"searchbox"|"separator"|"slider"|"spinbutton"|"status"|"strong"|"subscript"|"superscript"|"switch"|"tab"|"table"|"tablist"|"tabpanel"|"term"|"textbox"|"time"|"timer"|"toolbar"|"tooltip"|"tree"|"treegrid"|"treeitem", options?: {
+ /**
+ * An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.
+ *
+ * Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).
+ */
+ checked?: boolean;
+
+ /**
+ * Option to match the [accessible description](https://w3c.github.io/accname/#dfn-accessible-description). By
+ * default, matching is case-insensitive and searches for a substring, use
+ * [`exact`](https://playwright.dev/docs/api/class-by#by-role-option-exact) to control this behavior.
+ *
+ * Learn more about [accessible description](https://w3c.github.io/accname/#dfn-accessible-description).
+ */
+ description?: string|RegExp;
+
+ /**
+ * An attribute that is usually set by `aria-disabled` or `disabled`.
+ *
+ * **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about
+ * [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).
+ *
+ */
+ disabled?: boolean;
+
+ /**
+ * Whether [`name`](https://playwright.dev/docs/api/class-by#by-role-option-name) and
+ * [`description`](https://playwright.dev/docs/api/class-by#by-role-option-description) are matched exactly:
+ * case-sensitive and whole-string. Defaults to false. Ignored when the value is a regular expression. Note that exact
+ * match still trims whitespace.
+ */
+ exact?: boolean;
+
+ /**
+ * An attribute that is usually set by `aria-expanded`.
+ *
+ * Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).
+ */
+ expanded?: boolean;
+
+ /**
+ * Option that controls whether hidden elements are matched. By default, only non-hidden elements, as
+ * [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.
+ *
+ * Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).
+ */
+ includeHidden?: boolean;
+
+ /**
+ * A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values
+ * for `<h1>-<h6>` elements.
+ *
+ * Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).
+ */
+ level?: number;
+
+ /**
+ * Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is
+ * case-insensitive and searches for a substring, use
+ * [`exact`](https://playwright.dev/docs/api/class-by#by-role-option-exact) to control this behavior.
+ *
+ * Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
+ */
+ name?: string|RegExp;
+
+ /**
+ * An attribute that is usually set by `aria-pressed`.
+ *
+ * Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).
+ */
+ pressed?: boolean;
+
+ /**
+ * An attribute that is usually set by `aria-selected`.
+ *
+ * Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).
+ */
+ selected?: boolean;
+ }): By;
+
+ /**
+ * Matches an element by the test id. The test id attribute is resolved when the
+ * [By](https://playwright.dev/docs/api/class-by) is bound to a page, so a
+ * [By](https://playwright.dev/docs/api/class-by) built at module scope still honours
+ * [selectors.setTestIdAttribute(attributeName)](https://playwright.dev/docs/api/class-selectors#selectors-set-test-id-attribute)
+ * and the `testIdAttribute` option.
+ * @param testId Id to locate the element by.
+ */
+ testId(testId: string|RegExp): By;
+
+ /**
+ * Matches an element containing the given text.
+ * @param text Text to locate the element for.
+ * @param options
+ */
+ text(text: string|RegExp, options?: {
+ /**
+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
+ * regular expression. Note that exact match still trims whitespace.
+ */
+ exact?: boolean;
+ }): By;
+
+ /**
+ * Matches an element by its `title` attribute.
+ * @param text Text to locate the element for.
+ * @param options
+ */
+ title(text: string|RegExp, options?: {
+ /**
+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
+ * regular expression. Note that exact match still trims whitespace.
+ */
+ exact?: boolean;
+ }): By;
+}
+
/**
* Accurately simulating time-dependent behavior is essential for verifying the correctness of applications. Learn
* more about [clock emulation](https://playwright.dev/docs/clock).
@@ -21394,6 +21812,41 @@ export interface FrameLocator {
*/
frameLocator(selector: string): FrameLocator;
+ /**
+ * Binds a page-free [By](https://playwright.dev/docs/api/class-by) locator, returning a
+ * [Locator](https://playwright.dev/docs/api/class-locator) scoped to this object.
+ *
+ * **Usage**
+ *
+ * Consider a page object that describes elements without a page:
+ *
+ * ```js
+ * // todo-page.ts
+ * import { by } from '@playwright/test';
+ *
+ * export const newTodo = by.placeholder('What needs to be done?');
+ * export const todoItems = by.testId('todo-list').role('listitem');
+ * ```
+ *
+ * ```js
+ * import { expect, test } from '@playwright/test';
+ * import { newTodo, todoItems } from './todo-page';
+ *
+ * test('adds a todo', async ({ page }) => {
+ * await page.get(newTodo).fill('buy milk');
+ * await expect(page.get(todoItems)).toHaveCount(1);
+ * });
+ * ```
+ *
+ * **Details**
+ *
+ * The resolved [Locator](https://playwright.dev/docs/api/class-locator) is the same one the equivalent `getBy*` chain
+ * would produce, so `page.get(by.testId('list').text('Row'))` and `page.getByTestId('list').getByText('Row')` match
+ * the same element.
+ * @param by Page-free locator built with [playwright.by](https://playwright.dev/docs/api/class-playwright#playwright-by).
+ */
+ get(by: By): Locator;
+
/**
* Allows locating elements by their alt text.
*
@@ -22161,6 +22614,26 @@ export interface Mouse {
wheel(deltaX: number, deltaY: number): Promise<void>;
}
+/**
+ * Builds page-free locators that are resolved with
+ * [page.get(by)](https://playwright.dev/docs/api/class-page#page-get),
+ * [frame.get(by)](https://playwright.dev/docs/api/class-frame#frame-get) or
+ * [locator.get(by)](https://playwright.dev/docs/api/class-locator#locator-get). See
+ * [By](https://playwright.dev/docs/api/class-by) for details.
+ *
+ * ```js
+ * import { by, test } from '@playwright/test';
+ *
+ * const saveButton = by.role('button', { name: 'Save' });
+ *
+ * test('saves', async ({ page }) => {
+ * await page.get(saveButton).click();
+ * });
+ * ```
+ *
+ */
+export const by: By;
+
/**
* This object can be used to launch or connect to Chromium, returning instances of
* [Browser](https://playwright.dev/docs/api/class-browser).
diff --git a/packages/playwright-core/index.mjs b/packages/playwright-core/index.mjs
index 3b3c75b0f7..7344963f76 100644
--- a/packages/playwright-core/index.mjs
+++ b/packages/playwright-core/index.mjs
@@ -16,6 +16,7 @@
import playwright from './index.js';
+export const by = playwright.by;
export const chromium = playwright.chromium;
export const firefox = playwright.firefox;
export const webkit = playwright.webkit;
diff --git a/packages/playwright-core/src/client/frame.ts b/packages/playwright-core/src/client/frame.ts
index b665295bf0..a7789601c1 100644
--- a/packages/playwright-core/src/client/frame.ts
+++ b/packages/playwright-core/src/client/frame.ts
@@ -19,6 +19,7 @@ import fs from 'fs';
import { assertionAbortedMessage } from '@isomorphic/abortSignal';
import { assert } from '@isomorphic/assert';
+import { resolveBy } from '@isomorphic/by';
import { getByAltTextSelector, getByLabelSelector, getByPlaceholderSelector, getByRoleSelector, getByTestIdSelector, getByTextSelector, getByTitleSelector } from '@isomorphic/locatorUtils';
import { urlMatches } from '@isomorphic/urlMatch';
import { EventEmitter } from './eventEmitter';
@@ -40,6 +41,7 @@ import type { Page } from './page';
import type { DropPayload, FilePayload, LifecycleEvent, SelectOption, SelectOptionOptions, StrictOptions, TimeoutOptions, WaitForFunctionOptions } from './types';
import type * as structs from '../../types/structs';
import type * as api from '../../types/types';
+import type { By } from '@isomorphic/by';
import type { ByRoleOptions } from '@isomorphic/locatorUtils';
import type { URLMatch } from '@isomorphic/urlMatch';
import type * as channels from './channels';
@@ -365,6 +367,10 @@ export class Frame extends ChannelOwner<channels.FrameChannel> implements api.Fr
return new Locator(this, selector, options);
}
+ get(by: By): Locator {
+ return this.locator(resolveBy(by, testIdAttributeName()));
+ }
+
getByTestId(testId: string | RegExp): Locator {
return this.locator(getByTestIdSelector(testIdAttributeName(), testId));
}
diff --git a/packages/playwright-core/src/client/locator.ts b/packages/playwright-core/src/client/locator.ts
index 8be9d2b102..f93f30f0c5 100644
--- a/packages/playwright-core/src/client/locator.ts
+++ b/packages/playwright-core/src/client/locator.ts
@@ -16,6 +16,7 @@
import { inspect } from 'util';
+import { resolveBy } from '@isomorphic/by';
import { asLocatorDescription, locatorCustomDescription } from '@isomorphic/locatorGenerators';
import { getByAltTextSelector, getByLabelSelector, getByPlaceholderSelector, getByRoleSelector, getByTestIdSelector, getByTextSelector, getByTitleSelector } from '@isomorphic/locatorUtils';
import { escapeForTextSelector } from '@isomorphic/stringUtils';
@@ -31,6 +32,7 @@ import type { EvaluateOptions } from './jsHandle';
import type { DropPayload, FilePayload, FrameExpectParams, Rect, SelectOption, SelectOptionOptions, TimeoutOptions } from './types';
import type * as structs from '../../types/structs';
import type * as api from '../../types/types';
+import type { By } from '@isomorphic/by';
import type { ByRoleOptions } from '@isomorphic/locatorUtils';
import type * as channels from './channels';
@@ -178,6 +180,10 @@ export class Locator implements api.Locator {
return new Locator(this._frame, this._selector + ' >> internal:chain=' + JSON.stringify(selectorOrLocator._selector), options);
}
+ get(by: By): Locator {
+ return this.locator(resolveBy(by, testIdAttributeName()));
+ }
+
getByTestId(testId: string | RegExp): Locator {
return this.locator(getByTestIdSelector(testIdAttributeName(), testId));
}
@@ -457,6 +463,10 @@ export class FrameLocator implements api.FrameLocator {
return new Locator(this._frame, this._childSelector(selectorOrLocator._selector), options);
}
+ get(by: By): Locator {
+ return this.locator(resolveBy(by, testIdAttributeName()));
+ }
+
getByTestId(testId: string | RegExp): Locator {
return this.locator(getByTestIdSelector(testIdAttributeName(), testId));
}
diff --git a/packages/playwright-core/src/client/page.ts b/packages/playwright-core/src/client/page.ts
index d7ea623f7d..a6ab10d2aa 100644
--- a/packages/playwright-core/src/client/page.ts
+++ b/packages/playwright-core/src/client/page.ts
@@ -59,6 +59,7 @@ import type { RouteHandlerCallback, WebSocketRouteHandlerCallback } from './netw
import type { FilePayload, Headers, LifecycleEvent, SelectOption, SelectOptionOptions, Size, TimeoutOptions, WaitForEventOptions, WaitForFunctionOptions } from './types';
import type * as structs from '../../types/structs';
import type * as api from '../../types/types';
+import type { By } from '@isomorphic/by';
import type { ByRoleOptions } from '@isomorphic/locatorUtils';
import type { URLMatch } from '@isomorphic/urlMatch';
import type * as channels from './channels';
@@ -751,6 +752,10 @@ export class Page extends ChannelOwner<channels.PageChannel> implements api.Page
return this.mainFrame().locator(selector, options);
}
+ get(by: By): Locator {
+ return this.mainFrame().get(by);
+ }
+
getByTestId(testId: string | RegExp): Locator {
return this.mainFrame().getByTestId(testId);
}
diff --git a/packages/playwright-core/src/client/playwright.ts b/packages/playwright-core/src/client/playwright.ts
index f2bd2773f4..ef3cd348e6 100644
--- a/packages/playwright-core/src/client/playwright.ts
+++ b/packages/playwright-core/src/client/playwright.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import { by } from '@isomorphic/by';
import { Android } from './android';
import { Browser } from './browser';
import { BrowserType } from './browserType';
@@ -24,11 +25,13 @@ import { APIRequest } from './fetch';
import { Selectors } from './selectors';
import type * as channels from './channels';
+import type { By } from '@isomorphic/by';
import type { LaunchOptions } from 'playwright-core';
export class Playwright extends ChannelOwner<channels.PlaywrightChannel> {
readonly _android: Android;
readonly _electron: Electron;
+ readonly by: By;
readonly chromium: BrowserType;
readonly firefox: BrowserType;
readonly webkit: BrowserType;
@@ -44,6 +47,7 @@ export class Playwright extends ChannelOwner<channels.PlaywrightChannel> {
constructor(parent: ChannelOwner, type: string, guid: string, initializer: channels.PlaywrightInitializer) {
super(parent, type, guid, initializer);
+ this.by = by;
this.request = new APIRequest(this);
this.chromium = BrowserType.from(initializer.chromium);
this.chromium._playwright = this;
diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.ts
index 48f2fb9293..97bf61e5a1 100644
--- a/packages/playwright-core/types/types.d.ts
+++ b/packages/playwright-core/types/types.d.ts
@@ -3011,6 +3011,41 @@ export interface Page {
*/
frames(): Array<Frame>;
+ /**
+ * Binds a page-free [By](https://playwright.dev/docs/api/class-by) locator, returning a
+ * [Locator](https://playwright.dev/docs/api/class-locator) scoped to this object.
+ *
+ * **Usage**
+ *
+ * Consider a page object that describes elements without a page:
+ *
+ * ```js
+ * // todo-page.ts
+ * import { by } from '@playwright/test';
+ *
+ * export const newTodo = by.placeholder('What needs to be done?');
+ * export const todoItems = by.testId('todo-list').role('listitem');
+ * ```
+ *
+ * ```js
+ * import { expect, test } from '@playwright/test';
+ * import { newTodo, todoItems } from './todo-page';
+ *
+ * test('adds a todo', async ({ page }) => {
+ * await page.get(newTodo).fill('buy milk');
+ * await expect(page.get(todoItems)).toHaveCount(1);
+ * });
+ * ```
+ *
+ * **Details**
+ *
+ * The resolved [Locator](https://playwright.dev/docs/api/class-locator) is the same one the equivalent `getBy*` chain
+ * would produce, so `page.get(by.testId('list').text('Row'))` and `page.getByTestId('list').getByText('Row')` match
+ * the same element.
+ * @param by Page-free locator built with [playwright.by](https://playwright.dev/docs/api/class-playwright#playwright-by).
+ */
+ get(by: By): Locator;
+
/**
* **NOTE** Use locator-based
* [locator.getAttribute(name[, options])](https://playwright.dev/docs/api/class-locator#locator-get-attribute)
@@ -7361,6 +7396,41 @@ export interface Frame {
*/
frameLocator(selector: string): FrameLocator;
+ /**
+ * Binds a page-free [By](https://playwright.dev/docs/api/class-by) locator, returning a
+ * [Locator](https://playwright.dev/docs/api/class-locator) scoped to this object.
+ *
+ * **Usage**
+ *
+ * Consider a page object that describes elements without a page:
+ *
+ * ```js
+ * // todo-page.ts
+ * import { by } from '@playwright/test';
+ *
+ * export const newTodo = by.placeholder('What needs to be done?');
+ * export const todoItems = by.testId('todo-list').role('listitem');
+ * ```
+ *
+ * ```js
+ * import { expect, test } from '@playwright/test';
+ * import { newTodo, todoItems } from './todo-page';
+ *
+ * test('adds a todo', async ({ page }) => {
+ * await page.get(newTodo).fill('buy milk');
+ * await expect(page.get(todoItems)).toHaveCount(1);
+ * });
+ * ```
+ *
+ * **Details**
+ *
+ * The resolved [Locator](https://playwright.dev/docs/api/class-locator) is the same one the equivalent `getBy*` chain
+ * would produce, so `page.get(by.testId('list').text('Row'))` and `page.getByTestId('list').getByText('Row')` match
+ * the same element.
+ * @param by Page-free locator built with [playwright.by](https://playwright.dev/docs/api/class-playwright#playwright-by).
+ */
+ get(by: By): Locator;
+
/**
* **NOTE** Use locator-based
* [locator.getAttribute(name[, options])](https://playwright.dev/docs/api/class-locator#locator-get-attribute)
@@ -15437,6 +15507,41 @@ export interface Locator {
*/
frameLocator(selector: string): FrameLocator;
+ /**
+ * Binds a page-free [By](https://playwright.dev/docs/api/class-by) locator, returning a
+ * [Locator](https://playwright.dev/docs/api/class-locator) scoped to this object.
+ *
+ * **Usage**
+ *
+ * Consider a page object that describes elements without a page:
+ *
+ * ```js
+ * // todo-page.ts
+ * import { by } from '@playwright/test';
+ *
+ * export const newTodo = by.placeholder('What needs to be done?');
+ * export const todoItems = by.testId('todo-list').role('listitem');
+ * ```
+ *
+ * ```js
+ * import { expect, test } from '@playwright/test';
+ * import { newTodo, todoItems } from './todo-page';
+ *
+ * test('adds a todo', async ({ page }) => {
+ * await page.get(newTodo).fill('buy milk');
+ * await expect(page.get(todoItems)).toHaveCount(1);
+ * });
+ * ```
+ *
+ * **Details**
+ *
+ * The resolved [Locator](https://playwright.dev/docs/api/class-locator) is the same one the equivalent `getBy*` chain
+ * would produce, so `page.get(by.testId('list').text('Row'))` and `page.getByTestId('list').getByText('Row')` match
+ * the same element.
+ * @param by Page-free locator built with [playwright.by](https://playwright.dev/docs/api/class-playwright#playwright-by).
+ */
+ get(by: By): Locator;
+
/**
* Returns the matching element's attribute value.
*
@@ -20438,6 +20543,319 @@ export interface BrowserServer {
[Symbol.asyncDispose](): Promise<void>;
}
+/**
+ * [By](https://playwright.dev/docs/api/class-by) describes an element without being bound to a
+ * [Page](https://playwright.dev/docs/api/class-page) or a [Frame](https://playwright.dev/docs/api/class-frame). It is
+ * built with the top-level [playwright.by](https://playwright.dev/docs/api/class-playwright#playwright-by) object and
+ * turned into a regular [Locator](https://playwright.dev/docs/api/class-locator) with
+ * [page.get(by)](https://playwright.dev/docs/api/class-page#page-get),
+ * [frame.get(by)](https://playwright.dev/docs/api/class-frame#frame-get) or
+ * [locator.get(by)](https://playwright.dev/docs/api/class-locator#locator-get).
+ *
+ * Since a [By](https://playwright.dev/docs/api/class-by) carries no page, it can be defined once at module scope and
+ * reused by every test, which makes it a natural fit for page objects.
+ *
+ * **Usage**
+ *
+ * ```js
+ * import { by, expect, test } from '@playwright/test';
+ *
+ * const saveButton = by.role('button', { name: 'Save' });
+ * const todoItems = by.testId('todo-list').role('listitem');
+ *
+ * test('saves a todo', async ({ page }) => {
+ * await page.get(saveButton).click();
+ * await expect(page.get(todoItems)).toHaveCount(1);
+ * });
+ * ```
+ *
+ * A [By](https://playwright.dev/docs/api/class-by) chain resolves to the same element as the matching
+ * [Locator](https://playwright.dev/docs/api/class-locator) chain, so `page.get(by.testId('list').text('Row'))` and
+ * `page.getByTestId('list').getByText('Row')` are interchangeable. Chaining composes rather than replaces:
+ * `page.get(outer.get(inner))` and `page.get(outer).get(inner)` describe the same element.
+ */
+export interface By {
+ /**
+ * Matches a descendant element by its `alt` text.
+ * @param text Text to locate the element for.
+ * @param options
+ */
+ altText(text: string|RegExp, options?: {
+ /**
+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
+ * regular expression. Note that exact match still trims whitespace.
+ */
+ exact?: boolean;
+ }): By;
+
+ /**
+ * Narrows down the match to elements that match both this and the given
+ * [By](https://playwright.dev/docs/api/class-by).
+ *
+ * **Usage**
+ *
+ * ```js
+ * const saveButton = by.role('button').and(by.title('Subscribe'));
+ * ```
+ *
+ * @param by Additional locator to match.
+ */
+ and(by: By): By;
+
+ /**
+ * Describes the element, the description is used in the trace viewer and the reports.
+ * @param description Locator description.
+ */
+ describe(description: string): By;
+
+ /**
+ * Narrows down the match according to the options, for example filters by text. It can be chained to filter multiple
+ * times.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const rowWithButton = by.get('tr')
+ * .filter({ hasText: 'text in column 1' })
+ * .filter({ has: by.role('button', { name: 'column 2 button' }) });
+ * ```
+ *
+ * @param options
+ */
+ filter(options?: {
+ /**
+ * Narrows down the results to those which contain elements matching this relative
+ * [By](https://playwright.dev/docs/api/class-by). The inner [By](https://playwright.dev/docs/api/class-by) is queried
+ * starting with the outer match, not the document root.
+ */
+ has?: By;
+
+ /**
+ * Matches elements that do not contain an element matching this relative
+ * [By](https://playwright.dev/docs/api/class-by). The inner [By](https://playwright.dev/docs/api/class-by) is queried
+ * starting with the outer match, not the document root.
+ */
+ hasNot?: By;
+
+ /**
+ * Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
+ * When passed a [string], matching is case-insensitive and searches for a substring.
+ */
+ hasNotText?: string|RegExp;
+
+ /**
+ * Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
+ * passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
+ * `<article><div>Playwright</div></article>`.
+ */
+ hasText?: string|RegExp;
+
+ /**
+ * Only matches visible or invisible elements.
+ */
+ visible?: boolean;
+ }): By;
+
+ /**
+ * Matches the first matching element.
+ */
+ first(): By;
+
+ /**
+ * Matches a descendant element by a selector or by another [By](https://playwright.dev/docs/api/class-by).
+ *
+ * **Usage**
+ *
+ * ```js
+ * const firstCell = by.get('table').get('td').first();
+ *
+ * const listItem = by.role('listitem');
+ * const unread = by.testId('inbox').get(listItem).filter({ hasText: 'Unread' });
+ * ```
+ *
+ * **Details**
+ *
+ * Passing a [By](https://playwright.dev/docs/api/class-by) composes rather than replaces, so
+ * `outer.get(inner.get(innermost))` and `outer.get(inner).get(innermost)` describe the same element.
+ * @param selectorOrBy A selector or a [By](https://playwright.dev/docs/api/class-by) to match inside this one.
+ */
+ get(selectorOrBy: string|By): By;
+
+ /**
+ * Matches an input element by the text of the associated `<label>` or `aria-label` attribute.
+ * @param text Text to locate the element for.
+ * @param options
+ */
+ label(text: string|RegExp, options?: {
+ /**
+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
+ * regular expression. Note that exact match still trims whitespace.
+ */
+ exact?: boolean;
+ }): By;
+
+ /**
+ * Matches the last matching element.
+ */
+ last(): By;
+
+ /**
+ * Matches the n-th matching element. It is zero based, `nth(0)` selects the first element.
+ * @param index
+ */
+ nth(index: number): By;
+
+ /**
+ * Matches elements matching either this or the given [By](https://playwright.dev/docs/api/class-by).
+ *
+ * **Usage**
+ *
+ * ```js
+ * const dialogOrButton = by.role('dialog').or(by.role('button'));
+ * ```
+ *
+ * @param by Alternative locator to match.
+ */
+ or(by: By): By;
+
+ /**
+ * Matches an input element by the placeholder text.
+ * @param text Text to locate the element for.
+ * @param options
+ */
+ placeholder(text: string|RegExp, options?: {
+ /**
+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
+ * regular expression. Note that exact match still trims whitespace.
+ */
+ exact?: boolean;
+ }): By;
+
+ /**
+ * Matches an element by its [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
+ * [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
+ * [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
+ * @param role Required aria role.
+ * @param options
+ */
+ role(role: "alert"|"alertdialog"|"application"|"article"|"banner"|"blockquote"|"button"|"caption"|"cell"|"checkbox"|"code"|"columnheader"|"combobox"|"complementary"|"contentinfo"|"definition"|"deletion"|"dialog"|"directory"|"document"|"emphasis"|"feed"|"figure"|"form"|"generic"|"grid"|"gridcell"|"group"|"heading"|"img"|"insertion"|"link"|"list"|"listbox"|"listitem"|"log"|"main"|"marquee"|"math"|"meter"|"menu"|"menubar"|"menuitem"|"menuitemcheckbox"|"menuitemradio"|"navigation"|"none"|"note"|"option"|"paragraph"|"presentation"|"progressbar"|"radio"|"radiogroup"|"region"|"row"|"rowgroup"|"rowheader"|"scrollbar"|"search"|"searchbox"|"separator"|"slider"|"spinbutton"|"status"|"strong"|"subscript"|"superscript"|"switch"|"tab"|"table"|"tablist"|"tabpanel"|"term"|"textbox"|"time"|"timer"|"toolbar"|"tooltip"|"tree"|"treegrid"|"treeitem", options?: {
+ /**
+ * An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.
+ *
+ * Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).
+ */
+ checked?: boolean;
+
+ /**
+ * Option to match the [accessible description](https://w3c.github.io/accname/#dfn-accessible-description). By
+ * default, matching is case-insensitive and searches for a substring, use
+ * [`exact`](https://playwright.dev/docs/api/class-by#by-role-option-exact) to control this behavior.
+ *
+ * Learn more about [accessible description](https://w3c.github.io/accname/#dfn-accessible-description).
+ */
+ description?: string|RegExp;
+
+ /**
+ * An attribute that is usually set by `aria-disabled` or `disabled`.
+ *
+ * **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about
+ * [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).
+ *
+ */
+ disabled?: boolean;
+
+ /**
+ * Whether [`name`](https://playwright.dev/docs/api/class-by#by-role-option-name) and
+ * [`description`](https://playwright.dev/docs/api/class-by#by-role-option-description) are matched exactly:
+ * case-sensitive and whole-string. Defaults to false. Ignored when the value is a regular expression. Note that exact
+ * match still trims whitespace.
+ */
+ exact?: boolean;
+
+ /**
+ * An attribute that is usually set by `aria-expanded`.
+ *
+ * Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).
+ */
+ expanded?: boolean;
+
+ /**
+ * Option that controls whether hidden elements are matched. By default, only non-hidden elements, as
+ * [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.
+ *
+ * Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).
+ */
+ includeHidden?: boolean;
+
+ /**
+ * A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values
+ * for `<h1>-<h6>` elements.
+ *
+ * Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).
+ */
+ level?: number;
+
+ /**
+ * Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is
+ * case-insensitive and searches for a substring, use
+ * [`exact`](https://playwright.dev/docs/api/class-by#by-role-option-exact) to control this behavior.
+ *
+ * Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
+ */
+ name?: string|RegExp;
+
+ /**
+ * An attribute that is usually set by `aria-pressed`.
+ *
+ * Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).
+ */
+ pressed?: boolean;
+
+ /**
+ * An attribute that is usually set by `aria-selected`.
+ *
+ * Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).
+ */
+ selected?: boolean;
+ }): By;
+
+ /**
+ * Matches an element by the test id. The test id attribute is resolved when the
+ * [By](https://playwright.dev/docs/api/class-by) is bound to a page, so a
+ * [By](https://playwright.dev/docs/api/class-by) built at module scope still honours
+ * [selectors.setTestIdAttribute(attributeName)](https://playwright.dev/docs/api/class-selectors#selectors-set-test-id-attribute)
+ * and the `testIdAttribute` option.
+ * @param testId Id to locate the element by.
+ */
+ testId(testId: string|RegExp): By;
+
+ /**
+ * Matches an element containing the given text.
+ * @param text Text to locate the element for.
+ * @param options
+ */
+ text(text: string|RegExp, options?: {
+ /**
+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
+ * regular expression. Note that exact match still trims whitespace.
+ */
+ exact?: boolean;
+ }): By;
+
+ /**
+ * Matches an element by its `title` attribute.
+ * @param text Text to locate the element for.
+ * @param options
+ */
+ title(text: string|RegExp, options?: {
+ /**
+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
+ * regular expression. Note that exact match still trims whitespace.
+ */
+ exact?: boolean;
+ }): By;
+}
+
/**
* Accurately simulating time-dependent behavior is essential for verifying the correctness of applications. Learn
* more about [clock emulation](https://playwright.dev/docs/clock).
@@ -21394,6 +21812,41 @@ export interface FrameLocator {
*/
frameLocator(selector: string): FrameLocator;
+ /**
+ * Binds a page-free [By](https://playwright.dev/docs/api/class-by) locator, returning a
+ * [Locator](https://playwright.dev/docs/api/class-locator) scoped to this object.
+ *
+ * **Usage**
+ *
+ * Consider a page object that describes elements without a page:
+ *
+ * ```js
+ * // todo-page.ts
+ * import { by } from '@playwright/test';
+ *
+ * export const newTodo = by.placeholder('What needs to be done?');
+ * export const todoItems = by.testId('todo-list').role('listitem');
+ * ```
+ *
+ * ```js
+ * import { expect, test } from '@playwright/test';
+ * import { newTodo, todoItems } from './todo-page';
+ *
+ * test('adds a todo', async ({ page }) => {
+ * await page.get(newTodo).fill('buy milk');
+ * await expect(page.get(todoItems)).toHaveCount(1);
+ * });
+ * ```
+ *
+ * **Details**
+ *
+ * The resolved [Locator](https://playwright.dev/docs/api/class-locator) is the same one the equivalent `getBy*` chain
+ * would produce, so `page.get(by.testId('list').text('Row'))` and `page.getByTestId('list').getByText('Row')` match
+ * the same element.
+ * @param by Page-free locator built with [playwright.by](https://playwright.dev/docs/api/class-playwright#playwright-by).
+ */
+ get(by: By): Locator;
+
/**
* Allows locating elements by their alt text.
*
@@ -22161,6 +22614,26 @@ export interface Mouse {
wheel(deltaX: number, deltaY: number): Promise<void>;
}
+/**
+ * Builds page-free locators that are resolved with
+ * [page.get(by)](https://playwright.dev/docs/api/class-page#page-get),
+ * [frame.get(by)](https://playwright.dev/docs/api/class-frame#frame-get) or
+ * [locator.get(by)](https://playwright.dev/docs/api/class-locator#locator-get). See
+ * [By](https://playwright.dev/docs/api/class-by) for details.
+ *
+ * ```js
+ * import { by, test } from '@playwright/test';
+ *
+ * const saveButton = by.role('button', { name: 'Save' });
+ *
+ * test('saves', async ({ page }) => {
+ * await page.get(saveButton).click();
+ * });
+ * ```
+ *
+ */
+export const by: By;
+
/**
* This object can be used to launch or connect to Chromium, returning instances of
* [Browser](https://playwright.dev/docs/api/class-browser).
diff --git a/packages/playwright/test.mjs b/packages/playwright/test.mjs
index 69c5f6459b..865b2f53c8 100644
--- a/packages/playwright/test.mjs
+++ b/packages/playwright/test.mjs
@@ -16,6 +16,7 @@
import playwright from './test.js';
+export const by = playwright.by;
export const chromium = playwright.chromium;
export const firefox = playwright.firefox;
export const webkit = playwright.webkit;
diff --git a/tests/page/locator-get.spec.ts b/tests/page/locator-get.spec.ts
new file mode 100644
index 0000000000..e8c496e6da
--- /dev/null
+++ b/tests/page/locator-get.spec.ts
@@ -0,0 +1,127 @@
+/**
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { by } from 'playwright-core';
+
+import { test as it, expect } from './pageTest';
+
+it('should build the same locators the getBy* factories build', async ({ page }) => {
+ expect(page.get(by.altText('Alt')).toString()).toBe(page.getByAltText('Alt').toString());
+ expect(page.get(by.label('Label')).toString()).toBe(page.getByLabel('Label').toString());
+ expect(page.get(by.placeholder('Placeholder')).toString()).toBe(page.getByPlaceholder('Placeholder').toString());
+ expect(page.get(by.role('button', { name: 'Save' })).toString()).toBe(page.getByRole('button', { name: 'Save' }).toString());
+ expect(page.get(by.testId('id')).toString()).toBe(page.getByTestId('id').toString());
+ expect(page.get(by.text('Text', { exact: true })).toString()).toBe(page.getByText('Text', { exact: true }).toString());
+ expect(page.get(by.title('Title')).toString()).toBe(page.getByTitle('Title').toString());
+});
+
+it('should chain the same way locators chain', async ({ page }) => {
+ const chained = page.getByTestId('list').getByRole('listitem').filter({ hasText: 'Row' }).first();
+ expect(page.get(by.testId('list').role('listitem').filter({ hasText: 'Row' }).first()).toString()).toBe(chained.toString());
+});
+
+it('should compose get() the same way as chaining', async ({ page }) => {
+ const row = by.role('listitem');
+ const label = by.text('Label');
+ expect(page.get(by.testId('list').get(row.get(label))).toString()).toBe(page.get(by.testId('list').get(row).get(label)).toString());
+});
+
+it('should accept a selector in get()', async ({ page }) => {
+ expect(page.get(by.get('#outer')).toString()).toBe(page.locator('#outer').toString());
+ expect(page.get(by.get('#outer').get('span')).toString()).toBe(page.locator('#outer').locator('span').toString());
+
+ await page.setContent(`<div id=outer><span>Hello</span><span>World</span></div>`);
+ await expect(page.get(by.get('#outer').get('span'))).toHaveText(['Hello', 'World']);
+ await expect(page.get(by.get('#outer').get(by.text('World')))).toHaveText('World');
+ await expect(page.get(by.text('World').get('..'))).toHaveId('outer');
+});
+
+it('should work on page, frame and locator', async ({ page }) => {
+ await page.setContent(`<div id=outer><div data-testid="Hello">Hello world</div></div>`);
+ const hello = by.testId('Hello');
+ await expect(page.get(hello)).toHaveText('Hello world');
+ await expect(page.mainFrame().get(hello)).toHaveText('Hello world');
+ await expect(page.locator('#outer').get(hello)).toHaveText('Hello world');
+});
+
+it('should work inside a frame locator', async ({ page, server }) => {
+ await page.goto(server.PREFIX + '/frames/one-frame.html');
+ await expect(page.frameLocator('iframe').get(by.get('div'))).toHaveText(`Hi, I'm frame`);
+});
+
+it('should resolve the test id attribute when bound, not when built', async ({ page, playwright }) => {
+ const hello = by.testId('Hello');
+ await page.setContent('<div data-my-custom-testid="Hello">Hello world</div>');
+ playwright.selectors.setTestIdAttribute('data-my-custom-testid');
+ await expect(page.get(hello)).toHaveText('Hello world');
+});
+
+it('should resolve the test id attribute in nested and filter positions', async ({ page, playwright }) => {
+ const row = by.get('li').filter({ has: by.testId('unread') }).get(by.text('Subject'));
+ await page.setContent(`
+ <ul>
+ <li><span>Subject</span></li>
+ <li><i data-pw="unread"></i><span>Subject</span></li>
+ </ul>
+ `);
+ playwright.selectors.setTestIdAttribute('data-pw');
+ await expect(page.get(row)).toHaveCount(1);
+});
+
+it('should filter by has, hasNot, hasText, hasNotText and visible', async ({ page }) => {
+ await page.setContent(`
+ <div class=item><span>one</span><b>keep</b></div>
+ <div class=item><span>two</span></div>
+ <div class=item style="display: none"><span>one</span><b>keep</b></div>
+ `);
+ await expect(page.get(by.get('.item').filter({ has: by.get('b') }))).toHaveCount(2);
+ await expect(page.get(by.get('.item').filter({ hasNot: by.get('b') }))).toHaveCount(1);
+ await expect(page.get(by.get('.item').filter({ hasText: 'two' }))).toHaveCount(1);
+ await expect(page.get(by.get('.item').filter({ hasNotText: 'two' }))).toHaveCount(2);
+ await expect(page.get(by.get('.item').filter({ visible: true }))).toHaveCount(2);
+});
+
+it('should support and, or, nth, first and last', async ({ page }) => {
+ await page.setContent(`
+ <button title=Subscribe>one</button>
+ <button>two</button>
+ <div role=button>three</div>
+ `);
+ await expect(page.get(by.role('button').and(by.title('Subscribe')))).toHaveText('one');
+ await expect(page.get(by.role('button').or(by.get('div')))).toHaveCount(3);
+ await expect(page.get(by.role('button').nth(1))).toHaveText('two');
+ await expect(page.get(by.role('button').first())).toHaveText('one');
+ await expect(page.get(by.role('button').last())).toHaveText('three');
+});
+
+it('should describe the locator', async ({ page }) => {
+ await page.setContent(`<button>Save</button>`);
+ const saveButton = page.get(by.role('button').describe('save button'));
+ await expect(saveButton).toHaveText('Save');
+ expect(saveButton.description()).toBe('save button');
+});
+
+it('should be reusable and never mutated by chaining', async ({ page }) => {
+ await page.setContent(`<ul><li>A</li><li>B</li></ul>`);
+ const list = by.get('ul');
+ await expect(page.get(list.text('A'))).toHaveText('A');
+ await expect(page.get(list.text('B'))).toHaveText('B');
+ await expect(page.get(list)).toHaveText('AB');
+});
+
+it('should throw for an empty by', async ({ page }) => {
+ expect(() => page.get(by)).toThrow(/Empty "by" locator/);
+});
diff --git a/tests/playwright-test/playwright.config.spec.ts b/tests/playwright-test/playwright.config.spec.ts
index 025a160e34..8970797e6f 100644
--- a/tests/playwright-test/playwright.config.spec.ts
+++ b/tests/playwright-test/playwright.config.spec.ts
@@ -216,6 +216,33 @@ test('should respect testIdAttribute', async ({ runInlineTest }) => {
expect(result.passed).toBe(1);
});
+test('should respect testIdAttribute in a module-scope by locator', async ({ runInlineTest }) => {
+ const result = await runInlineTest({
+ 'playwright.config.ts': `
+ module.exports = {
+ use: {
+ testIdAttribute: 'data-pw',
+ }
+ };
+ `,
+ 'page-object.ts': `
+ import { by } from '@playwright/test';
+ export const myId = by.testId('myid');
+ `,
+ 'a.test.ts': `
+ import { test, expect } from '@playwright/test';
+ import { myId } from './page-object';
+ test('pass', async ({ page }) => {
+ await page.setContent('<div data-pw="myid">Hi</div>');
+ await expect(page.get(myId)).toHaveText('Hi');
+ });
+ `,
+ }, { workers: 1 });
+
+ expect(result.exitCode).toBe(0);
+ expect(result.passed).toBe(1);
+});
+
test('should respect testIdAttribute with multiple comma-separated names', async ({ runInlineTest }) => {
const result = await runInlineTest({
'playwright.config.ts': `