All files / webdriverio/src/commands/browser keys.js

100% Statements 15/15
100% Branches 6/6
100% Functions 4/4
100% Lines 13/13

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                                                          8x         8x 4x 4x 1x 6x     3x           5x 4x           6x 6x   1x       1x    
/**
 *
 * Send a sequence of key strokes to the active element. You can also use characters like
 * "Left arrow" or "Back space". WebdriverIO will take care of translating them into unicode
 * characters. You’ll find all supported characters [here](https://w3c.github.io/webdriver/webdriver-spec.html#keyboard-actions).
 * To do that, the value has to correspond to a key from the table.
 *
 * Modifier like Ctrl, Shift, Alt and Meta will stay pressed so you need to trigger them again to release them.
 *
 * <example>
    :keys.js
    it('copies text out of active element', () => {
        // copies text from an input element
        const input = $('#username')
        input.setValue('anonymous')
 
        browser.keys(['Meta', 'a'])
        browser.keys(['Meta', 'c'])
    });
 * </example>
 *
 * @param {String|String[]} value  The sequence of keys to type. An array or string must be provided.
 * @see https://w3c.github.io/webdriver/#dispatching-actions
 *
 */
 
import { checkUnicode } from '../../utils'
 
export default function keys (value) {
    let keySequence = []
 
    /**
     * replace key with corresponding unicode character
     */
    if (typeof value === 'string') {
        keySequence = checkUnicode(value)
    } else if (value instanceof Array) {
        for (const charSet of value) {
            keySequence = keySequence.concat(checkUnicode(charSet))
        }
    } else {
        throw new Error('"keys" command requires a string or array of strings as parameter')
    }
 
    /**
     * JsonWireProtocol action
     */
    if (!this.isW3C) {
        return this.sendKeys(keySequence)
    }
 
    /**
     * W3C way of handle it key actions
     */
    const keyDownActions = keySequence.map((value) => ({ type: 'keyDown', value }))
    const keyUpActions = keySequence.map((value) => ({ type: 'keyUp', value }))
 
    return this.performActions([{
        type: 'key',
        id: 'keyboard',
        actions: [...keyDownActions, ...keyUpActions]
    }]).then(() => this.releaseActions())
}