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(select): allow to select options by value/label/id/index (#46)
Dmitry Gozman7783400156d0
diff --git a/docs/api.md b/docs/api.mdindex 6476d7b577..cd7afc2793 100644--- a/docs/api.md+++ b/docs/api.md@@ -1615,16 +1615,29 @@ Page is guaranteed to have a main frame which persists during navigations.> **NOTE** Screenshots take at least 1/6 second on OS X. See https://crbug.com/741689 for discussion.#### page.select(selector, ...values)-- `selector` <[string]> A [selector] to query page for-- `...values` <...[string]> Values of options to select. If the `<select>` has the `multiple` attribute, all values are considered, otherwise only the first one is taken into account.+- `selector` <[string]> A [selector] to query page for.+- `...values` <...[string]|[Object]> Options to select. If the `<select>` has the `multiple` attribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are equivalent to `{value:'string'}`. Option is considered matching if all specified properties match.+ - `value` <[string]> Matches by `option.value`.+ - `label` <[string]> Matches by `option.label`.+ - `id` <[string]> Matches by `option.id`.+ - `index` <[number]> Matches by the index.- returns: <[Promise]<[Array]<[string]>>> An array of option values that have been successfully selected.Triggers a `change` and `input` event once all the provided options have been selected.If there's no `<select>` element matching `selector`, the method throws an error.```js-page.select('select#colors', 'blue'); // single selection-page.select('select#colors', 'red', 'green', 'blue'); // multiple selections+// single selection matching the value+page.select('select#colors', 'blue');++// single selection matching both the value and the label+page.select('select#colors', { value: 'blue', label: 'Blue' });++// multiple selection+page.select('select#colors', 'red', 'green', 'blue');++// multiple selection for blue, red and second option+page.select('select#colors', { value: 'blue' }, { index: 2 }, 'red');```Shortcut for [page.mainFrame().select()](#frameselectselector-values)@@ -2809,16 +2822,29 @@ If the name is empty, returns the id attribute instead.- returns: <?[Frame]> Parent frame, if any. Detached frames and main frames return `null`.#### frame.select(selector, ...values)-- `selector` <[string]> A [selector] to query frame for-- `...values` <...[string]> Values of options to select. If the `<select>` has the `multiple` attribute, all values are considered, otherwise only the first one is taken into account.+- `selector` <[string]> A [selector] to query frame for.+- `...values` <...[string]|[Object]> Options to select. If the `<select>` has the `multiple` attribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are equivalent to `{value:'string'}`. Option is considered matching if all specified properties match.+ - `value` <[string]> Matches by `option.value`.+ - `label` <[string]> Matches by `option.label`.+ - `id` <[string]> Matches by `option.id`.+ - `index` <[number]> Matches by the index.- returns: <[Promise]<[Array]<[string]>>> An array of option values that have been successfully selected.Triggers a `change` and `input` event once all the provided options have been selected.If there's no `<select>` element matching `selector`, the method throws an error.```js-frame.select('select#colors', 'blue'); // single selection-frame.select('select#colors', 'red', 'green', 'blue'); // multiple selections+// single selection matching the value+frame.select('select#colors', 'blue');++// single selection matching both the value and the label+frame.select('select#colors', { value: 'blue', label: 'Blue' });++// multiple selection+frame.select('select#colors', 'red', 'green', 'blue');++// multiple selection matching blue, red and second option+frame.select('select#colors', { value: 'blue' }, { index: 2 }, 'red');```#### frame.setContent(html[, options])@@ -3523,15 +3549,28 @@ This method scrolls element into view if needed, and then uses [page.screenshot]If the element is detached from DOM, the method throws an error.#### elementHandle.select(...values)-- `...values` <...[string]> Values of options to select. If the `<select>` has the `multiple` attribute, all values are considered, otherwise only the first one is taken into account.+- `...values` <...[string]|[Object]> Options to select. If the `<select>` has the `multiple` attribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are equivalent to `{value:'string'}`. Option is considered matching if all specified properties match.+ - `value` <[string]> Matches by `option.value`.+ - `label` <[string]> Matches by `option.label`.+ - `id` <[string]> Matches by `option.id`.+ - `index` <[number]> Matches by the index.- returns: <[Promise]<[Array]<[string]>>> An array of option values that have been successfully selected.Triggers a `change` and `input` event once all the provided options have been selected.If element is not a `<select>` element, the method throws an error.```js-handle.select('blue'); // single selection-handle.select('red', 'green', 'blue'); // multiple selections+// single selection matching the value+handle.select('blue');++// single selection matching both the value and the label+handle.select({ value: 'blue', label: 'Blue' });++// multiple selection+handle.select('red', 'green', 'blue');++// multiple selection for blue, red and second option+handle.select({ value: 'blue' }, { index: 2 }, 'red');```#### elementHandle.toString()diff --git a/src/chromium/DOMWorld.ts b/src/chromium/DOMWorld.tsindex 3bb442d66e..6ac039c4a0 100644--- a/src/chromium/DOMWorld.ts+++ b/src/chromium/DOMWorld.ts@@ -21,7 +21,7 @@ import { ExecutionContext } from './ExecutionContext';import { Frame } from './Frame';import { FrameManager } from './FrameManager';import { assert, helper } from '../helper';-import { ElementHandle, JSHandle, ClickOptions, PointerActionOptions, MultiClickOptions } from './JSHandle';+import { ElementHandle, JSHandle, ClickOptions, PointerActionOptions, MultiClickOptions, SelectOption } from './JSHandle';import { LifecycleWatcher } from './LifecycleWatcher';import { TimeoutSettings } from '../TimeoutSettings';const readFileAsync = helper.promisify(fs.readFile);@@ -322,7 +322,7 @@ export class DOMWorld {await handle.dispose();}- async select(selector: string, ...values: string[]): Promise<string[]> {+ async select(selector: string, ...values: (string | SelectOption)[]): Promise<string[]> {const handle = await this.$(selector);assert(handle, 'No node found for selector: ' + selector);const result = await handle.select(...values);diff --git a/src/chromium/Frame.ts b/src/chromium/Frame.tsindex 6067ef2d71..07511f656d 100644--- a/src/chromium/Frame.ts+++ b/src/chromium/Frame.ts@@ -20,7 +20,7 @@ import { CDPSession } from './Connection';import { DOMWorld } from './DOMWorld';import { ExecutionContext } from './ExecutionContext';import { FrameManager } from './FrameManager';-import { ClickOptions, ElementHandle, JSHandle, MultiClickOptions, PointerActionOptions } from './JSHandle';+import { ClickOptions, ElementHandle, JSHandle, MultiClickOptions, PointerActionOptions, SelectOption } from './JSHandle';import { Response } from './NetworkManager';import { Protocol } from './protocol';@@ -164,7 +164,7 @@ export class Frame {return this._secondaryWorld.hover(selector, options);}- select(selector: string, ...values: string[]): Promise<string[]>{+ select(selector: string, ...values: (string | SelectOption)[]): Promise<string[]>{return this._secondaryWorld.select(selector, ...values);}diff --git a/src/chromium/JSHandle.ts b/src/chromium/JSHandle.tsindex 2fbcf6b45d..630ab4f5ac 100644--- a/src/chromium/JSHandle.ts+++ b/src/chromium/JSHandle.ts@@ -47,6 +47,13 @@ export type MultiClickOptions = PointerActionOptions & {button?: Button;};+export type SelectOption = {+ value?: string;+ id?: string;+ label?: string;+ index?: number;+};+export function createJSHandle(context: ExecutionContext, remoteObject: Protocol.Runtime.RemoteObject) {const frame = context.frame();if (remoteObject.subtype === 'node' && frame) {@@ -317,24 +324,45 @@ export class ElementHandle extends JSHandle {return this._performPointerAction(point => this._page.mouse.tripleclick(point.x, point.y, options), options);}- async select(...values: string[]): Promise<string[]> {- for (const value of values)- assert(helper.isString(value), 'Values must be strings. Found value "' + value + '" of type "' + (typeof value) + '"');- return this.evaluate((element: HTMLSelectElement, values: string[]) => {+ async select(...values: (string | SelectOption)[]): Promise<string[]> {+ const options = values.map(value => typeof value === 'object' ? value : { value });+ for (const option of options) {+ if (option.value !== undefined)+ assert(helper.isString(option.value), 'Values must be strings. Found value "' + option.value + '" of type "' + (typeof option.value) + '"');+ if (option.label !== undefined)+ assert(helper.isString(option.label), 'Labels must be strings. Found label "' + option.label + '" of type "' + (typeof option.label) + '"');+ if (option.id !== undefined)+ assert(helper.isString(option.id), 'Ids must be strings. Found id "' + option.id + '" of type "' + (typeof option.id) + '"');+ if (option.index !== undefined)+ assert(helper.isNumber(option.index), 'Indices must be numbers. Found index "' + option.index + '" of type "' + (typeof option.index) + '"');+ }+ return this.evaluate((element: HTMLSelectElement, optionsToSelect: SelectOption[]) => {if (element.nodeName.toLowerCase() !== 'select')throw new Error('Element is not a <select> element.');const options = Array.from(element.options);element.value = undefined;- for (const option of options) {- option.selected = values.includes(option.value);+ for (let index = 0; index < options.length; index++) {+ const option = options[index];+ option.selected = optionsToSelect.some(optionToSelect => {+ let matches = true;+ if (optionToSelect.value !== undefined)+ matches = matches && optionToSelect.value === option.value;+ if (optionToSelect.label !== undefined)+ matches = matches && optionToSelect.label === option.label;+ if (optionToSelect.id !== undefined)+ matches = matches && optionToSelect.id === option.id;+ if (optionToSelect.index !== undefined)+ matches = matches && optionToSelect.index === index;+ return matches;+ });if (option.selected && !element.multiple)break;}element.dispatchEvent(new Event('input', { 'bubbles': true }));element.dispatchEvent(new Event('change', { 'bubbles': true }));return options.filter(option => option.selected).map(option => option.value);- }, values);+ }, options);}async fill(value: string): Promise<void> {diff --git a/src/chromium/Page.ts b/src/chromium/Page.tsindex a86b370c64..c99a926a38 100644--- a/src/chromium/Page.ts+++ b/src/chromium/Page.ts@@ -33,7 +33,7 @@ import { PDF } from './features/pdf';import { Frame } from './Frame';import { FrameManager, FrameManagerEvents } from './FrameManager';import { Keyboard, Mouse } from './Input';-import { ClickOptions, createJSHandle, ElementHandle, JSHandle, MultiClickOptions, PointerActionOptions } from './JSHandle';+import { ClickOptions, createJSHandle, ElementHandle, JSHandle, MultiClickOptions, PointerActionOptions, SelectOption } from './JSHandle';import { NetworkManagerEvents, Response } from './NetworkManager';import { Protocol } from './protocol';import { getExceptionMessage, releaseObject, valueFromRemoteObject } from './protocolHelper';@@ -715,7 +715,7 @@ export class Page extends EventEmitter {return this.mainFrame().hover(selector, options);}- select(selector: string, ...values: string[]): Promise<string[]> {+ select(selector: string, ...values: (string | SelectOption)[]): Promise<string[]> {return this.mainFrame().select(selector, ...values);}diff --git a/test/assets/input/select.html b/test/assets/input/select.htmlindex 879a537a76..53dd06adf6 100644--- a/test/assets/input/select.html+++ b/test/assets/input/select.html@@ -18,7 +18,7 @@<option value="purple">Purple</option><option value="red">Red</option><option value="violet">Violet</option>- <option value="white">White</option>+ <option value="white" id="whiteOption">White</option><option value="yellow">Yellow</option></select><script>diff --git a/test/page.spec.js b/test/page.spec.jsindex 4a800a634f..6adbf95a78 100644--- a/test/page.spec.js+++ b/test/page.spec.js@@ -890,6 +890,41 @@ module.exports.addTests = function({testRunner, expect, headless, playwright, FFexpect(await page.evaluate(() => result.onInput)).toEqual(['blue']);expect(await page.evaluate(() => result.onChange)).toEqual(['blue']);});+ it('should select single option by value', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/select.html');+ await page.select('select', { value: 'blue' });+ expect(await page.evaluate(() => result.onInput)).toEqual(['blue']);+ expect(await page.evaluate(() => result.onChange)).toEqual(['blue']);+ });+ it('should select single option by label', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/select.html');+ await page.select('select', { label: 'Indigo' });+ expect(await page.evaluate(() => result.onInput)).toEqual(['indigo']);+ expect(await page.evaluate(() => result.onChange)).toEqual(['indigo']);+ });+ it('should select single option by id', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/select.html');+ await page.select('select', { id: 'whiteOption' });+ expect(await page.evaluate(() => result.onInput)).toEqual(['white']);+ expect(await page.evaluate(() => result.onChange)).toEqual(['white']);+ });+ it('should select single option by index', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/select.html');+ await page.select('select', { index: 2 });+ expect(await page.evaluate(() => result.onInput)).toEqual(['brown']);+ expect(await page.evaluate(() => result.onChange)).toEqual(['brown']);+ });+ it('should select single option by multiple attributes', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/select.html');+ await page.select('select', { value: 'green', label: 'Green' });+ expect(await page.evaluate(() => result.onInput)).toEqual(['green']);+ expect(await page.evaluate(() => result.onChange)).toEqual(['green']);+ });+ it('should not select single option when some attributes do not match', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/select.html');+ await page.select('select', { value: 'green', label: 'Brown' });+ expect(await page.evaluate(() => document.querySelector('select').value)).toEqual('');+ });it('should select only first option', async({page, server}) => {await page.goto(server.PREFIX + '/input/select.html');await page.select('select', 'blue', 'green', 'red');@@ -912,6 +947,13 @@ module.exports.addTests = function({testRunner, expect, headless, playwright, FFexpect(await page.evaluate(() => result.onInput)).toEqual(['blue', 'green', 'red']);expect(await page.evaluate(() => result.onChange)).toEqual(['blue', 'green', 'red']);});+ it('should select multiple options with attributes', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/select.html');+ await page.evaluate(() => makeMultiple());+ await page.select('select', 'blue', { label: 'Green' }, { index: 4 });+ expect(await page.evaluate(() => result.onInput)).toEqual(['blue', 'gray', 'green']);+ expect(await page.evaluate(() => result.onChange)).toEqual(['blue', 'gray', 'green']);+ });it('should respect event bubbling', async({page, server}) => {await page.goto(server.PREFIX + '/input/select.html');await page.select('select', 'blue');@@ -958,15 +1000,49 @@ module.exports.addTests = function({testRunner, expect, headless, playwright, FFawait page.select('select');expect(await page.$eval('select', select => Array.from(select.options).every(option => !option.selected))).toEqual(true);});- it('should throw if passed in non-strings', async({page, server}) => {+ it('should throw if passed wrong types', async({page, server}) => {+ let error;await page.setContent('<select><option value="12"/></select>');- let error = null;++ error = null;try {await page.select('select', 12);} catch (e) {error = e;}expect(error.message).toContain('Values must be strings');++ error = null;+ try {+ await page.select('select', { value: 12 });+ } catch (e) {+ error = e;+ }+ expect(error.message).toContain('Values must be strings');++ error = null;+ try {+ await page.select('select', { label: 12 });+ } catch (e) {+ error = e;+ }+ expect(error.message).toContain('Labels must be strings');++ error = null;+ try {+ await page.select('select', { id: 12 });+ } catch (e) {+ error = e;+ }+ expect(error.message).toContain('Ids must be strings');++ error = null;+ try {+ await page.select('select', { index: '12' });+ } catch (e) {+ error = e;+ }+ expect(error.message).toContain('Indices must be numbers');});// @see https://github.com/GoogleChrome/puppeteer/issues/3327it.skip(FFOX || WEBKIT)('should work when re-defining top-level Event class', async({page, server}) => {diff --git a/utils/doclint/check_public_api/MDBuilder.js b/utils/doclint/check_public_api/MDBuilder.jsindex bc3776aed5..2a349b0e00 100644--- a/utils/doclint/check_public_api/MDBuilder.js+++ b/utils/doclint/check_public_api/MDBuilder.js@@ -57,7 +57,7 @@ class MDOutline {const properties = [];const comment = str.substring(str.indexOf('<') + type.length + 2).trim();// Strings have enum values instead of properties- if (!type.includes('string')) {+ if (type !== 'string' && type !== 'string|number' && type !== 'string|Array<string>' && type !== 'Array<string>') {for (const childElement of element.querySelectorAll(':scope > ul > li')) {const property = parseProperty(childElement);property.required = property.comment.includes('***required***');