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

100% Statements 8/8
100% Branches 6/6
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                                                                        4x 1x           3x   3x 1x     2x 1x           1x    
/**
 *
 * Select option with a specific index.
 *
 * <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>
    :selectByIndex.js
    it('Should demonstrate the selectByIndex command', () => {
        const selectBox = $('#selectbox');
        console.log(selectBox.getValue()); // returns "someValue0"
        selectBox.selectByIndex(4);
        console.log(selectBox.getValue()); // returns "someValue4"
    });
 * </example>
 *
 * @alias element.selectByIndexs
 * @param {Number} index      option index
 * @uses protocol/findElementsFromElement, protocol/elementClick
 * @type action
 *
 */
 
import { getElementFromResponse } from '../../utils'
 
export default async function selectByIndex (index) {
    /**
     * negative index check
     */
    if (index < 0) {
        throw new Error('Index needs to be 0 or any other positive number')
    }
 
    /**
    * get option elememnts using css
    */
    const optionElements = await this.findElementsFromElement(this.elementId, 'css selector',  'option')
 
    if (optionElements.length === 0) {
        throw new Error('Select element doesn\'t contain any option element')
    }
 
    if (optionElements.length - 1 < index) {
        throw new Error(`Option with index "${index}" not found. Select element only contains ${optionElements.length} option elements`)
    }
 
    /**
    * select option
    */
    return this.elementClick(getElementFromResponse(optionElements[index]))
}