feat(Page.select): return selected options from Page.select (#1099)

This patch teaches Page.select to return an array of actually selected options.
If no option is selected, an empty array will be returned.
This commit is contained in:
AlexChung1995
2017-10-31 21:47:52 -07:00
committed by Andrey Lushnikov
parent 9f19641a3d
commit e70f98ddb9
3 changed files with 50 additions and 27 deletions

View File

@@ -779,22 +779,19 @@ class Page extends EventEmitter {
/**
* @param {string} selector
* @param {!Array<string>} values
* @return {!Promise<!Array<string>>}
*/
async select(selector, ...values) {
await this.$eval(selector, (element, values) => {
return await this.$eval(selector, (element, values) => {
if (element.nodeName.toLowerCase() !== 'select')
throw new Error('Element is not a <select> element.');
const options = Array.from(element.options);
if (element.multiple) {
for (const option of options)
option.selected = values.includes(option.value);
} else {
element.value = values.shift();
}
element.value = undefined;
for (const option of options)
option.selected = values.includes(option.value);
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);
}