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(locator): introduce locator.describe() (#35969)
Pavel Feldman313de29fab72
diff --git a/docs/src/api/class-locator.md b/docs/src/api/class-locator.mdindex 8fbd60651c..5ab1c3989b 100644--- a/docs/src/api/class-locator.md+++ b/docs/src/api/class-locator.md@@ -580,6 +580,19 @@ When all steps combined have not finished during the specified [`option: timeout### option: Locator.dblclick.trial = %%-input-trial-with-modifiers-%%* since: v1.14+## method: Locator.describe+* since: v1.53+- returns: <[Locator]>++Describes the locator, description is used in the trace viewer and reports.+Returns the locator pointing to the same element.++### param: Locator.describe.description+* since: v1.53+- `description` <[string]>++Locator description.+## async method: Locator.dispatchEvent* since: v1.14diff --git a/packages/html-reporter/src/treeItem.tsx b/packages/html-reporter/src/treeItem.tsxindex 7ae9b840f8..546510afc3 100644--- a/packages/html-reporter/src/treeItem.tsx+++ b/packages/html-reporter/src/treeItem.tsx@@ -29,7 +29,7 @@ export const TreeItem: React.FunctionComponent<{flash?: boolean}> = ({ title, loadChildren, onClick, expandByDefault, depth, style, flash }) => {const [expanded, setExpanded] = React.useState(expandByDefault || false);- return <div className={clsx('tree-item', flash && 'yellow-flash')} style={style}>+ return <div role='treeitem' className={clsx('tree-item', flash && 'yellow-flash')} style={style}><span className='tree-item-title' style={{ whiteSpace: 'nowrap', paddingLeft: depth * 22 + 4 }} onClick={() => { onClick?.(); setExpanded(!expanded); }} >{loadChildren && !!expanded && icons.downArrow()}{loadChildren && !expanded && icons.rightArrow()}diff --git a/packages/injected/src/injectedScript.ts b/packages/injected/src/injectedScript.tsindex f276fdec5e..b60b442b18 100644--- a/packages/injected/src/injectedScript.ts+++ b/packages/injected/src/injectedScript.ts@@ -227,6 +227,7 @@ export class InjectedScript {this._engines.set('internal:attr', this._createNamedAttributeEngine());this._engines.set('internal:testid', this._createNamedAttributeEngine());this._engines.set('internal:role', createRoleEngine(true));+ this._engines.set('internal:describe', this._createDescribeEngine());this._engines.set('aria-ref', this._createAriaRefEngine());for (const { name, source } of options.customEngines)@@ -479,6 +480,15 @@ export class InjectedScript {return { queryAll };}+ private _createDescribeEngine(): SelectorEngine {+ const queryAll = (root: SelectorRoot): Element[] => {+ if (root.nodeType !== 1 /* Node.ELEMENT_NODE */)+ return [];+ return [root as Element];+ };+ return { queryAll };+ }+private _createControlEngine(): SelectorEngine {return {queryAll(root: SelectorRoot, body: any) {diff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.tsindex 8be78eea88..cd23c6702f 100644--- a/packages/playwright-client/types/types.d.ts+++ b/packages/playwright-client/types/types.d.ts@@ -12910,6 +12910,13 @@ export interface Locator {trial?: boolean;}): Promise<void>;+ /**+ * Describes the locator, description is used in the trace viewer and reports. Returns the locator pointing to the+ * same element.+ * @param description Locator description.+ */+ describe(description: string): Locator;+/*** Programmatically dispatch an event on the matching element.*diff --git a/packages/playwright-core/src/client/locator.ts b/packages/playwright-core/src/client/locator.tsindex 9a25653f7f..eff5193bcc 100644--- a/packages/playwright-core/src/client/locator.ts+++ b/packages/playwright-core/src/client/locator.ts@@ -210,6 +210,10 @@ export class Locator implements api.Locator {return new FrameLocator(this._frame, this._selector);}+ describe(description: string) {+ return new Locator(this._frame, this._selector + ' >> internal:describe=' + JSON.stringify(description));+ }+first(): Locator {return new Locator(this._frame, this._selector + ' >> nth=0');}diff --git a/packages/playwright-core/src/server/selectors.ts b/packages/playwright-core/src/server/selectors.tsindex ff377ee3d3..822e9b0a80 100644--- a/packages/playwright-core/src/server/selectors.ts+++ b/packages/playwright-core/src/server/selectors.ts@@ -41,7 +41,9 @@ export class Selectors {'internal:has', 'internal:has-not','internal:has-text', 'internal:has-not-text','internal:and', 'internal:or', 'internal:chain',- 'role', 'internal:attr', 'internal:label', 'internal:text', 'internal:role', 'internal:testid', 'aria-ref'+ 'role', 'internal:attr', 'internal:label', 'internal:text',+ 'internal:role', 'internal:testid', 'internal:describe',+ 'aria-ref']);this._builtinEnginesInMainWorld = new Set(['_react', '_vue',diff --git a/packages/playwright-core/src/utils/isomorphic/locatorGenerators.ts b/packages/playwright-core/src/utils/isomorphic/locatorGenerators.tsindex 5be1f36b96..9769eca0fb 100644--- a/packages/playwright-core/src/utils/isomorphic/locatorGenerators.ts+++ b/packages/playwright-core/src/utils/isomorphic/locatorGenerators.ts@@ -37,6 +37,14 @@ export interface LocatorFactory {chainLocators(locators: string[]): string;}+export function asLocatorDescription(selector: string): string | undefined {+ const parsed = parseSelector(selector);+ const describe = parsed.parts.findLast(part => part.name === 'internal:describe');+ if (describe)+ return JSON.parse(describe.body as string);+ return undefined;+}+export function asLocator(lang: Language, selector: string, isFrameLocator: boolean = false): string {return asLocators(lang, selector, isFrameLocator, 1)[0];}@@ -59,6 +67,8 @@ function innerAsLocators(factory: LocatorFactory, parsed: ParsedSelector, isFramconst base = nextBase;nextBase = 'locator';+ if (part.name === 'internal:describe')+ continue;if (part.name === 'nth') {if (part.body === '0')tokens.push([factory.generateLocator(base, 'first', ''), factory.generateLocator(base, 'nth', '0')]);diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.tsindex 8be78eea88..cd23c6702f 100644--- a/packages/playwright-core/types/types.d.ts+++ b/packages/playwright-core/types/types.d.ts@@ -12910,6 +12910,13 @@ export interface Locator {trial?: boolean;}): Promise<void>;+ /**+ * Describes the locator, description is used in the trace viewer and reports. Returns the locator pointing to the+ * same element.+ * @param description Locator description.+ */+ describe(description: string): Locator;+/*** Programmatically dispatch an event on the matching element.*diff --git a/packages/playwright/src/index.ts b/packages/playwright/src/index.tsindex 8370382bb3..ec70869b61 100644--- a/packages/playwright/src/index.ts+++ b/packages/playwright/src/index.ts@@ -18,7 +18,7 @@ import fs from 'fs';import path from 'path';import * as playwrightLibrary from 'playwright-core';-import { setBoxedStackPrefixes, asLocator, createGuid, currentZone, debugMode, isString, jsonStringifyForceASCII } from 'playwright-core/lib/utils';+import { setBoxedStackPrefixes, createGuid, currentZone, debugMode, isString, jsonStringifyForceASCII, asLocator, asLocatorDescription } from 'playwright-core/lib/utils';import { currentTestInfo } from './common/globals';import { rootTestType } from './common/testType';@@ -761,6 +761,7 @@ function paramsToRender(apiName: string) {return ['url', 'selector', 'text', 'key'];}}+function renderApiCall(apiName: string, params: any) {if (apiName === 'tracing.group')return params.name;@@ -769,14 +770,24 @@ function renderApiCall(apiName: string, params: any) {for (const name of paramsToRender(apiName)) {if (!(name in params))continue;- let value;- if (name === 'selector' && isString(params[name]) && params[name].startsWith('internal:')) {- const getter = asLocator('javascript', params[name]);- apiName = apiName.replace(/^locator\./, 'locator.' + getter + '.');- apiName = apiName.replace(/^page\./, 'page.' + getter + '.');- apiName = apiName.replace(/^frame\./, 'frame.' + getter + '.');+ if (name === 'selector' && isString(params[name])) {+ const description = asLocatorDescription(params[name]);+ if (description) {+ const replacement = JSON.stringify(description);+ apiName = apiName.replace(/^locator\.(.*)/, `$1 ${replacement}`);+ apiName = apiName.replace(/^page\.(.*)/, `$1 ${replacement}`);+ apiName = apiName.replace(/^frame\.(.*)/, `$1 ${replacement}`);+ } else if (params[name].startsWith('internal:')) {+ const replacement = asLocator('javascript', params[name]) + '.';+ apiName = apiName.replace(/^locator\./, replacement);+ apiName = apiName.replace(/^page\./, replacement);+ apiName = apiName.replace(/^frame\./, replacement);+ } else {+ const value = params[name];+ paramsArray.push(value);+ }} else {- value = params[name];+ const value = params[name];paramsArray.push(value);}}diff --git a/packages/trace-viewer/src/ui/actionList.tsx b/packages/trace-viewer/src/ui/actionList.tsxindex 4f3a8128e8..042cd320d4 100644--- a/packages/trace-viewer/src/ui/actionList.tsx+++ b/packages/trace-viewer/src/ui/actionList.tsx@@ -19,7 +19,7 @@ import { clsx, msToString } from '@web/uiUtils';import * as React from 'react';import './actionList.css';import * as modelUtil from './modelUtil';-import { asLocator, type Language } from '@isomorphic/locatorGenerators';+import { asLocatorDescription, asLocator, type Language } from '@isomorphic/locatorGenerators';import type { TreeState } from '@web/components/treeView';import { TreeView } from '@web/components/treeView';import type { ActionTraceEventInContext, ActionTreeItem } from './modelUtil';@@ -297,7 +297,7 @@ const actionParameterDisplayString = (if (!ignoreLocator && params.selector !== undefined) {return {type: 'locator',- value: asLocator(sdkLanguage, params.selector),+ value: asLocatorDescription(params.selector) ?? asLocator(sdkLanguage, params.selector),childDisplayString: actionParameterDisplayString(action,sdkLanguage,diff --git a/tests/library/trace-viewer.spec.ts b/tests/library/trace-viewer.spec.tsindex 18ed101e64..f329fb99d1 100644--- a/tests/library/trace-viewer.spec.ts+++ b/tests/library/trace-viewer.spec.ts@@ -1897,3 +1897,14 @@ test('should not trip over complex urls in style tags', {await expect(snapshot.locator('div')).toHaveCSS('color', 'rgb(1, 2, 3)');await expect(snapshot.locator('span')).toHaveCSS('color', 'rgb(4, 5, 6)');});++test('should render locator descriptions', async ({ runAndTrace, page }) => {+ const traceViewer = await runAndTrace(async () => {+ await page.setContent('<input type="text" />');+ await page.locator('input').describe('main input').click({ button: 'right' });+ });++ await expect(traceViewer.page.locator('body')).toMatchAriaSnapshot(`+ - treeitem /locator\\.clickmain input/+ `);+});diff --git a/tests/playwright-test/reporter-html.spec.ts b/tests/playwright-test/reporter-html.spec.tsindex ae3fa072f4..7707b549e0 100644--- a/tests/playwright-test/reporter-html.spec.ts+++ b/tests/playwright-test/reporter-html.spec.ts@@ -2956,6 +2956,25 @@ for (const useIntermediateMergeReport of [true, false] as const) {const prompt = await page.evaluate(() => navigator.clipboard.readText());expect(prompt, 'contains snapshot').toContain('- button "Click me"');});++ test('should render locator description', async ({ runInlineTest, showReport, page }) => {+ const result = await runInlineTest({+ 'example.spec.ts': `+ import { test, expect } from '@playwright/test';+ test('sample', async ({ browser }) => {+ const page = await browser.newPage();+ await page.setContent('<button>Click me</button>');+ await page.locator('button').describe('Click me').click();+ });+ `,+ }, { reporter: 'dot,html' }, { PLAYWRIGHT_HTML_OPEN: 'never' });+ expect(result.exitCode).toBe(0);+ await showReport();+ await page.getByRole('link', { name: 'sample' }).click();+ await expect(page.locator('body')).toMatchAriaSnapshot(`+ - treeitem "click \\\"Click me\\\""+ `);+ });});}diff --git a/tests/playwright-test/test-step.spec.ts b/tests/playwright-test/test-step.spec.tsindex a266bddcc7..a5bad3a293 100644--- a/tests/playwright-test/test-step.spec.ts+++ b/tests/playwright-test/test-step.spec.ts@@ -1217,7 +1217,7 @@ pw:api | apiRequest.newContextpw:api |page.waitForNavigation @ a.test.ts:5pw:api |page.goto(data:text/html,<button></button>) @ a.test.ts:6pw:api |page.click(button) @ a.test.ts:8-pw:api |locator.getByRole('button').click @ a.test.ts:9+pw:api |getByRole('button').click @ a.test.ts:9pw:api |apiRequestContext.get(${server.EMPTY_PAGE}) @ a.test.ts:10pw:api |↪ error: <error message>pw:api |apiRequestContext.get(${server.EMPTY_PAGE}) @ a.test.ts:11