Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
feat(test): allow testIdAttribute to be a comma-separated list of names (#40844)
Yury Semikhatskyfc39cf70bbcb
diff --git a/docs/src/api/class-selectors.md b/docs/src/api/class-selectors.mdindex 4c30114303..fefd7ba394 100644--- a/docs/src/api/class-selectors.md+++ b/docs/src/api/class-selectors.md@@ -247,4 +247,5 @@ Defines custom attribute name to be used in [`method: Page.getByTestId`]. `data-* since: v1.27- `attributeName` <[string]>-Test id attribute name.+Test id attribute name. To match elements with any of several attributes, pass them as a+comma-separated list, e.g. `"data-pw,data-ti"`.diff --git a/docs/src/test-api/class-testoptions.md b/docs/src/test-api/class-testoptions.mdindex 5573cd0a2c..62425a56c0 100644--- a/docs/src/test-api/class-testoptions.md+++ b/docs/src/test-api/class-testoptions.md@@ -540,7 +540,8 @@ test('not signed in test', async ({ page }) => {## property: TestOptions.testIdAttribute* since: v1.27-Custom attribute to be used in [`method: Page.getByTestId`]. `data-testid` is used by default.+Custom attribute to be used in [`method: Page.getByTestId`]. `data-testid` is used by default. To match+elements with any of several attributes, pass them as a comma-separated list.**Usage**@@ -554,6 +555,18 @@ export default defineConfig({});```+Multiple attributes:++```js title="playwright.config.ts"+import { defineConfig } from '@playwright/test';++export default defineConfig({+ use: {+ testIdAttribute: 'data-pw,data-ti',+ },+});+```+## property: TestOptions.timezoneId = %%-context-option-timezoneid-%%* since: v1.10diff --git a/packages/injected/src/injectedScript.ts b/packages/injected/src/injectedScript.tsindex 571a53bf57..0b3e9f4e58 100644--- a/packages/injected/src/injectedScript.ts+++ b/packages/injected/src/injectedScript.ts@@ -16,6 +16,7 @@import { parseAriaSnapshot } from '@isomorphic/ariaSnapshot';import { asLocator } from '@isomorphic/locatorGenerators';+import { splitTestIdAttributeNames } from '@isomorphic/locatorUtils';import { parseAttributeSelector, parseSelector, stringifySelector, visitAllSelectorParts } from '@isomorphic/selectorParser';import { cacheNormalizedWhitespaces, normalizeWhiteSpace, trimStringWithEllipsis } from '@isomorphic/stringUtils';@@ -35,7 +36,7 @@ import { UtilityScript } from './utilityScript';import type { AriaTemplateNode } from '@isomorphic/ariaSnapshot';import type { CSSComplexSelectorList } from '@isomorphic/cssParser';import type { Language } from '@isomorphic/locatorGenerators';-import type { NestedSelectorBody, ParsedSelector, ParsedSelectorPart } from '@isomorphic/selectorParser';+import type { AttributeSelectorPart, NestedSelectorBody, ParsedSelector, ParsedSelectorPart } from '@isomorphic/selectorParser';import type * as channels from '@protocol/channels';import type { AriaSnapshot, AriaTreeOptions } from './ariaSnapshot';import type { LayoutSelectorName } from './layoutSelectorUtils';@@ -228,7 +229,7 @@ export class InjectedScript {this._engines.set('internal:has-text', this._createInternalHasTextEngine());this._engines.set('internal:has-not-text', this._createInternalHasNotTextEngine());this._engines.set('internal:attr', this._createNamedAttributeEngine());- this._engines.set('internal:testid', this._createNamedAttributeEngine());+ this._engines.set('internal:testid', this._createTestIdEngine());this._engines.set('internal:role', createRoleEngine(true));this._engines.set('internal:describe', this._createDescribeEngine());this._engines.set('aria-ref', this._createAriaRefEngine());@@ -490,21 +491,31 @@ export class InjectedScript {const parsed = parseAttributeSelector(selector, true);if (parsed.name || parsed.attributes.length !== 1)throw new Error('Malformed attribute selector: ' + selector);- const { name, value, caseSensitive } = parsed.attributes[0];- const lowerCaseValue = caseSensitive ? null : value.toLowerCase();- let matcher: (s: string) => boolean;- if (value instanceof RegExp)- matcher = s => !!s.match(value);- else if (caseSensitive)- matcher = s => s === value;- else- matcher = s => s.toLowerCase().includes(lowerCaseValue!);+ const { name } = parsed.attributes[0];+ const matcher = createAttributeMatcher(parsed.attributes[0]);const elements = this._evaluator._queryCSS({ scope: root as Document | Element, pierceShadow: true }, `[${name}]`);return elements.filter(e => matcher(e.getAttribute(name)!));};return { queryAll };}+ private _createTestIdEngine(): SelectorEngine {+ const queryAll = (root: SelectorRoot, selector: string): Element[] => {+ const parsed = parseAttributeSelector(selector, true);+ if (parsed.name || parsed.attributes.length !== 1)+ throw new Error('Malformed test id selector: ' + selector);+ const names = splitTestIdAttributeNames(parsed.attributes[0].name);+ const matcher = createAttributeMatcher(parsed.attributes[0]);+ const cssQuery = names.map(n => `[${n}]`).join(',');+ const elements = this._evaluator._queryCSS({ scope: root as Document | Element, pierceShadow: true }, cssQuery);+ return elements.filter(e => names.some(n => {+ const actual = e.getAttribute(n);+ return actual !== null && matcher(actual);+ }));+ };+ return { queryAll };+ }+private _createDescribeEngine(): SelectorEngine {const queryAll = (root: SelectorRoot): Element[] => {if (root.nodeType !== 1 /* Node.ELEMENT_NODE */)@@ -1727,6 +1738,16 @@ function oneLine(s: string): string {return s.replace(/\n/g, '↵').replace(/\t/g, '⇆');}+function createAttributeMatcher(part: AttributeSelectorPart): (s: string) => boolean {+ const { value, caseSensitive } = part;+ if (value instanceof RegExp)+ return s => !!s.match(value);+ if (caseSensitive)+ return s => s === value;+ const lowerCaseValue = value.toLowerCase();+ return s => s.toLowerCase().includes(lowerCaseValue);+}+function cssUnquote(s: string): string {// Trim quotes.s = s.substring(1, s.length - 1);diff --git a/packages/injected/src/selectorGenerator.ts b/packages/injected/src/selectorGenerator.tsindex c7d40e7bea..bdacf765f2 100644--- a/packages/injected/src/selectorGenerator.ts+++ b/packages/injected/src/selectorGenerator.ts@@ -14,6 +14,7 @@* limitations under the License.*/+import { splitTestIdAttributeNames } from '@isomorphic/locatorUtils';import { escapeForAttributeSelector, escapeForTextSelector, escapeRegExp, quoteCSSAttributeValue } from '@isomorphic/stringUtils';import { beginDOMCaches, closestCrossShadow, endDOMCaches, isElementVisible, isInsideScope, parentElementOrShadowHost } from './domUtils';@@ -231,11 +232,12 @@ function generateSelectorFor(cache: Cache, injectedScript: InjectedScript, targefunction buildNoTextCandidates(injectedScript: InjectedScript, element: Element, options: InternalOptions): SelectorToken[] {const candidates: SelectorToken[] = [];+ const testIdAttributeNames = splitTestIdAttributeNames(options.testIdAttributeName);// CSS selectors are applicable to elements via locator() and iframes via frameLocator().{for (const attr of ['data-testid', 'data-test-id', 'data-test']) {- if (attr !== options.testIdAttributeName && element.getAttribute(attr))+ if (!testIdAttributeNames.includes(attr) && element.getAttribute(attr))candidates.push({ engine: 'css', selector: `[${attr}=${quoteCSSAttributeValue(element.getAttribute(attr)!)}]`, score: kOtherTestIdScore });}@@ -255,16 +257,20 @@ function buildNoTextCandidates(injectedScript: InjectedScript, element: Element,}// Locate by testId via CSS selector.- if (element.getAttribute(options.testIdAttributeName))- candidates.push({ engine: 'css', selector: `[${options.testIdAttributeName}=${quoteCSSAttributeValue(element.getAttribute(options.testIdAttributeName)!)}]`, score: kTestIdScore });+ for (const testIdAttr of testIdAttributeNames) {+ if (element.getAttribute(testIdAttr))+ candidates.push({ engine: 'css', selector: `[${testIdAttr}=${quoteCSSAttributeValue(element.getAttribute(testIdAttr)!)}]`, score: kTestIdScore });+ }penalizeScoreForLength([candidates]);return candidates;}// Everything below is not applicable to iframes (getBy* methods).- if (element.getAttribute(options.testIdAttributeName))- candidates.push({ engine: 'internal:testid', selector: `[${options.testIdAttributeName}=${escapeForAttributeSelector(element.getAttribute(options.testIdAttributeName)!, true)}]`, score: kTestIdScore });+ for (const testIdAttr of testIdAttributeNames) {+ if (element.getAttribute(testIdAttr))+ candidates.push({ engine: 'internal:testid', selector: `[${testIdAttr}=${escapeForAttributeSelector(element.getAttribute(testIdAttr)!, true)}]`, score: kTestIdScore });+ }if (element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') {const input = element as HTMLInputElement | HTMLTextAreaElement;diff --git a/packages/isomorphic/locatorParser.ts b/packages/isomorphic/locatorParser.tsindex ee98271f7a..35212cc571 100644--- a/packages/isomorphic/locatorParser.ts+++ b/packages/isomorphic/locatorParser.ts@@ -15,6 +15,7 @@*/import { asLocators } from './locatorGenerators';+import { encodeTestIdAttributeName } from './locatorUtils';import { parseSelector } from './selectorParser';import { escapeForAttributeSelector, escapeForTextSelector } from './stringUtils';@@ -165,7 +166,7 @@ function transform(template: string, params: TemplateParams, testIdAttributeName.replace(/getbyrole\(([^)]+)\)/g, 'internal:role=$1').replace(/getbytext\(([^)]+)\)/g, 'internal:text=$1').replace(/getbylabel\(([^)]+)\)/g, 'internal:label=$1')- .replace(/getbytestid\(([^)]+)\)/g, `internal:testid=[${testIdAttributeName}=$1]`)+ .replace(/getbytestid\(([^)]+)\)/g, `internal:testid=[${encodeTestIdAttributeName(testIdAttributeName)}=$1]`).replace(/getby(placeholder|alt|title)(?:text)?\(([^)]+)\)/g, 'internal:attr=[$1=$2]').replace(/first(\(\))?/g, 'nth=0').replace(/last(\(\))?/g, 'nth=-1')@@ -219,7 +220,7 @@ function transform(template: string, params: TemplateParams, testIdAttributeName}).join(' >> ');}-export function locatorOrSelectorAsSelector(language: Language, locator: string, testIdAttributeName: string): string {+export function locatorOrSelectorAsSelector(language: Language, locator: string, testIdAttributeName: string = 'data-testid'): string {try {return unsafeLocatorOrSelectorAsSelector(language, locator, testIdAttributeName);} catch (e) {@@ -227,7 +228,7 @@ export function locatorOrSelectorAsSelector(language: Language, locator: string,}}-export function unsafeLocatorOrSelectorAsSelector(language: Language, locator: string, testIdAttributeName: string): string {+export function unsafeLocatorOrSelectorAsSelector(language: Language, locator: string, testIdAttributeName: string = 'data-testid'): string {try {parseSelector(locator);return locator;diff --git a/packages/isomorphic/locatorUtils.ts b/packages/isomorphic/locatorUtils.tsindex 5007867920..77cb2d715a 100644--- a/packages/isomorphic/locatorUtils.ts+++ b/packages/isomorphic/locatorUtils.ts@@ -33,8 +33,17 @@ function getByAttributeTextSelector(attrName: string, text: string | RegExp, optreturn `internal:attr=[${attrName}=${escapeForAttributeSelector(text, options?.exact || false)}]`;}+// Multiple test id attribute names can be joined with a comma. Attribute names cannot contain commas.+export function splitTestIdAttributeNames(testIdAttributeName: string): string[] {+ return testIdAttributeName.split(',');+}++export function encodeTestIdAttributeName(testIdAttributeName: string): string {+ return testIdAttributeName.includes(',') ? JSON.stringify(testIdAttributeName) : testIdAttributeName;+}+export function getByTestIdSelector(testIdAttributeName: string, testId: string | RegExp): string {- return `internal:testid=[${testIdAttributeName}=${escapeForAttributeSelector(testId, true)}]`;+ return `internal:testid=[${encodeTestIdAttributeName(testIdAttributeName)}=${escapeForAttributeSelector(testId, true)}]`;}export function getByLabelSelector(text: string | RegExp, options?: { exact?: boolean }): string {diff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.tsindex 8ee8cce10c..1b17367221 100644--- a/packages/playwright-client/types/types.d.ts+++ b/packages/playwright-client/types/types.d.ts@@ -21304,7 +21304,8 @@ export interface Selectors {* Defines custom attribute name to be used in* [page.getByTestId(testId)](https://playwright.dev/docs/api/class-page#page-get-by-test-id). `data-testid` is used* by default.- * @param attributeName Test id attribute name.+ * @param attributeName Test id attribute name. To match elements with any of several attributes, pass them as a comma-separated list, e.g.+ * `"data-pw,data-ti"`.*/setTestIdAttribute(attributeName: string): void;}diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.tsindex 8ee8cce10c..1b17367221 100644--- a/packages/playwright-core/types/types.d.ts+++ b/packages/playwright-core/types/types.d.ts@@ -21304,7 +21304,8 @@ export interface Selectors {* Defines custom attribute name to be used in* [page.getByTestId(testId)](https://playwright.dev/docs/api/class-page#page-get-by-test-id). `data-testid` is used* by default.- * @param attributeName Test id attribute name.+ * @param attributeName Test id attribute name. To match elements with any of several attributes, pass them as a comma-separated list, e.g.+ * `"data-pw,data-ti"`.*/setTestIdAttribute(attributeName: string): void;}diff --git a/packages/playwright/types/test.d.ts b/packages/playwright/types/test.d.tsindex 7b45706f9b..b5d167754d 100644--- a/packages/playwright/types/test.d.ts+++ b/packages/playwright/types/test.d.ts@@ -7583,7 +7583,7 @@ export interface PlaywrightTestOptions {/*** Custom attribute to be used in* [page.getByTestId(testId)](https://playwright.dev/docs/api/class-page#page-get-by-test-id). `data-testid` is used- * by default.+ * by default. To match elements with any of several attributes, pass them as a comma-separated list.** **Usage***@@ -7598,6 +7598,19 @@ export interface PlaywrightTestOptions {* });* ```*+ * Multiple attributes:+ *+ * ```js+ * // playwright.config.ts+ * import { defineConfig } from '@playwright/test';+ *+ * export default defineConfig({+ * use: {+ * testIdAttribute: 'data-pw,data-ti',+ * },+ * });+ * ```+ **/testIdAttribute: string;}diff --git a/tests/library/inspector/cli-codegen-2.spec.ts b/tests/library/inspector/cli-codegen-2.spec.tsindex af403d56be..c1d09f7181 100644--- a/tests/library/inspector/cli-codegen-2.spec.ts+++ b/tests/library/inspector/cli-codegen-2.spec.ts@@ -494,6 +494,23 @@ await page.Locator("#textarea").FillAsync(\"Hello'\\"\`\\nWorld\");`);expect.soft(sources.get('C#')!.text).toContain(`await page.GetByTestId("foo").ClickAsync();`);});+ test('should generate getByTestId for any of the configured testIdAttributes', async ({ openRecorder }) => {+ const { page, recorder } = await openRecorder({ testIdAttributeName: 'data-pw,data-ti' });++ await recorder.setContentAndWait(`+ <button data-pw="primary">First</button>+ <button data-ti="secondary">Second</button>+ `);++ await page.click('[data-pw=primary]');+ let sources = await recorder.waitForOutput('JavaScript', `page.getByTestId('primary')`);+ expect.soft(sources.get('JavaScript')!.text).toContain(`await page.getByTestId('primary').click()`);++ await page.click('[data-ti=secondary]');+ sources = await recorder.waitForOutput('JavaScript', `page.getByTestId('secondary')`);+ expect.soft(sources.get('JavaScript')!.text).toContain(`await page.getByTestId('secondary').click()`);+ });+test('should auto-generate toBeVisible', async ({ openRecorder }) => {const { page, recorder } = await openRecorder();diff --git a/tests/page/selectors-get-by.spec.ts b/tests/page/selectors-get-by.spec.tsindex 3d191fef01..692de3cc7f 100644--- a/tests/page/selectors-get-by.spec.ts+++ b/tests/page/selectors-get-by.spec.ts@@ -31,6 +31,21 @@ it('getByTestId with custom testId should work', async ({ page, playwright }) =>await expect(page.locator('div').getByTestId('Hello')).toHaveText('Hello world');});+it('getByTestId with comma-separated testIdAttributes should match any', async ({ page, playwright }) => {+ await page.setContent(`+ <section>+ <div data-pw="Hello">first</div>+ <div data-ti="Hello">second</div>+ <div data-testid="Hello">third</div>+ </section>+ `);+ playwright.selectors.setTestIdAttribute('data-pw,data-ti');+ await expect(page.getByTestId('Hello')).toHaveCount(2);+ await expect(page.getByTestId('Hello')).toHaveText(['first', 'second']);+ await expect(page.mainFrame().getByTestId('Hello')).toHaveCount(2);+ await expect(page.locator('section').getByTestId('Hello')).toHaveCount(2);+});+it('getByTestId should escape id', async ({ page }) => {await page.setContent(`<div><div data-testid='He"llo'>Hello world</div></div>`);await expect(page.getByTestId('He"llo')).toHaveText('Hello world');diff --git a/tests/playwright-test/playwright.config.spec.ts b/tests/playwright-test/playwright.config.spec.tsindex 651cee0fd0..a168f8983b 100644--- a/tests/playwright-test/playwright.config.spec.ts+++ b/tests/playwright-test/playwright.config.spec.ts@@ -206,3 +206,30 @@ test('should respect testIdAttribute', async ({ runInlineTest }) => {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': `+ module.exports = {+ use: {+ testIdAttribute: 'data-pw,data-ti',+ }+ };+ `,+ 'a.test.ts': `+ import { test, expect } from '@playwright/test';+ test('pass', async ({ page }) => {+ await page.setContent(\`+ <div data-pw="myid">A</div>+ <div data-ti="myid">B</div>+ <div data-testid="myid">C</div>+ \`);+ await expect(page.getByTestId('myid')).toHaveCount(2);+ await expect(page.getByTestId('myid')).toHaveText(['A', 'B']);+ });+ `,+ }, { workers: 1 });++ expect(result.exitCode).toBe(0);+ expect(result.passed).toBe(1);+});