All files / webdriverio/src/commands/element selectByVisibleText.js

100% Statements 8/8
100% Branches 4/4
100% Functions 1/1
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68                                                                        6x       6x             6x     6x 6x   6x             6x         6x    
/**
 *
 * Select option with displayed text matching the argument.
 *
 * <example>
    :example.html
    <select id="selectbox">
        <option value="someValue0">uno</option>
        <option value="someValue1">dos</option>
        <option value="someValue2">tres</option>
        <option value="someValue3">cuatro</option>
        <option value="someValue4">cinco</option>
        <option value="someValue5">seis</option>
    </select>
    :selectByVisibleText.js
    it('demonstrate the selectByVisibleText command', () => {
        const selectBox = $('#selectbox');
        console.log(selectBox.getText('option:checked')); // returns "uno"
        selectBox.selectByVisibleText('cuatro');
        console.log(selectBox.getText('option:checked')); // returns "cuatro"
    })
 * </example>
 *
 * @alias element.selectByVisibleText
 * @param {String} text       text of option element to get selected
 * @uses protocol/findElementsFromElement, protocol/elementClick
 * @type action
 *
 */
 
import { getElementFromResponse } from '../../utils'
 
export default async function selectByVisibleText (text) {
    /**
     * convert value into string
     */
    text = typeof text === 'number'
        ? text.toString()
        : text
 
    const normalized = text
        .trim() // strip leading and trailing white-space characters
        .replace(/\s+/, ' ') // replace sequences of whitespace characters by a single space
 
    /**
    * find option element using xpath
    */
    const formatted = /"/.test(normalized)
        ? 'concat("' + normalized.split('"').join('", \'"\', "') + '")'
        : `"${normalized}"`
    const dotFormat = `[. = ${formatted}]`
    const spaceFormat = `[normalize-space(text()) = ${formatted}]`
 
    const selections = [
        `./option${dotFormat}`,
        `./option${spaceFormat}`,
        `./optgroup/option${dotFormat}`,
        `./optgroup/option${spaceFormat}`,
    ]
 
    const optionElement = await this.findElementFromElement(this.elementId, 'xpath', selections.join('|'))
 
    /**
    * select option
    */
    return this.elementClick(getElementFromResponse(optionElement))
}