All files / webdriverio/src/utils findStrategy.js

100% Statements 95/95
100% Branches 67/67
100% Functions 6/6
100% Lines 91/91

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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199      71x 71x 71x     71x     71x                     71x         303x 1x     302x 15x     1426x 3x     284x 1x     283x 1x     282x 1x     281x 5x     276x 4x     272x 1x         1080x 3x       268x 2x         266x 6x     260x 2x       1032x 18x     71x 303x 303x   303x     15x 15x 1x   14x 14x 14x     5x 5x     1x 1x 1x     1x 1x 1x     1x 1x 1x     5x 5x 5x     1x 1x 1x     4x 4x 4x     1x 1x 1x     3x 3x     2x 2x 2x     6x 4x 4x   6x     18x 72x 18x 18x           18x   18x 9x   18x 5x           18x     18x 18x             302x 1x     301x    
import { W3C_SELECTOR_STRATEGIES } from '../constants'
import isPlainObject from 'lodash.isplainobject'
 
const DEFAULT_STRATEGY = 'css selector'
const DIRECT_SELECTOR_REGEXP = /^(id|css selector|xpath|link text|partial link text|name|tag name|class name|-android uiautomator|-android datamatcher|-ios uiautomation|-ios predicate string|-ios class chain|accessibility id):(.+)/
const XPATH_SELECTORS_START = [
    '/', '(', '../', './', '*/'
]
const NAME_MOBILE_SELECTORS_START = [
    'uia', 'xcuielementtype', 'android.widget', 'cyi'
]
const XPATH_SELECTOR_REGEXP = [
    // HTML tag
    /^([a-z0-9|-]*)/,
    // optional . or # + class or id
    /(?:(\.|#)(-?[_a-zA-Z]+[_a-zA-Z0-9-]*))?/,
    // optional [attribute-name="attribute-selector"]
    /(?:\[(-?[_a-zA-Z]+[_a-zA-Z0-9-]*)(?:=(?:"|')([a-zA-z0-9\-_. ]+)(?:"|'))?\])?/,
    // *=query or =query
    /(\*)?=(.+)$/,
]
 
const defineStrategy = function (selector) {
    // Condition with checking isPlainObject(selector) should be first because
    // in case of "selector" argument is a plain object then .match() will cause
    // an error like "selector.match is not a function"
    // Use '-android datamatcher' strategy if selector is a plain object (Android only)
    if (isPlainObject(selector)) {
        return '-android datamatcher'
    }
    // Check if user has specified locator strategy directly
    if (selector.match(DIRECT_SELECTOR_REGEXP)) {
        return 'directly'
    }
    // Use xPath strategy if selector starts with //
    if (XPATH_SELECTORS_START.some(option => selector.startsWith(option))) {
        return 'xpath'
    }
    // Use link text strategy if selector starts with =
    if (selector.startsWith('=')) {
        return 'link text'
    }
    // Use partial link text strategy if selector starts with *=
    if (selector.startsWith('*=')) {
        return 'partial link text'
    }
    // Use id strategy if the selector starts with id=
    if (selector.startsWith('id=')) {
        return 'id'
    }
    // Recursive element search using the UiAutomator library (Android only)
    if (selector.startsWith('android=')) {
        return '-android uiautomator'
    }
    // Recursive element search using the UIAutomation library (iOS-only)
    if (selector.startsWith('ios=')) {
        return '-ios uiautomation'
    }
    // Recursive element search using accessibility id
    if (selector.startsWith('~')) {
        return 'accessibility id'
    }
    // Class name mobile selector
    // for iOS = UIA...
    // for Android = android.widget
    if (NAME_MOBILE_SELECTORS_START.some(option => selector.toLowerCase().startsWith(option))) {
        return 'class name'
    }
    // Use tag name strategy if selector contains a tag
    // e.g. "<div>" or "<div />"
    if (selector.search(/<[a-zA-Z-]+( \/)*>/g) >= 0) {
        return 'tag name'
    }
    // Use name strategy if selector queries elements with name attributes for JSONWP
    // or if isMobile is used even when w3c is used
    // e.g. "[name='myName']" or '[name="myName"]'
    if (selector.search(/^\[name=("|')([a-zA-z0-9\-_.@=[\] ']+)("|')]$/) >= 0) {
        return 'name'
    }
    // Allow to move up to the parent or select current element
    if (selector === '..' || selector === '.') {
        return 'xpath'
    }
    // Any element with given class, id, or attribute and content
    // e.g. h1.header=Welcome or [data-name=table-row]=Item or #content*=Intro
    if (selector.match(new RegExp(XPATH_SELECTOR_REGEXP.map(rx => rx.source).join('')))) {
        return 'xpath extended'
    }
}
export const findStrategy = function (selector, isW3C, isMobile) {
    let using = DEFAULT_STRATEGY
    let value = selector
 
    switch (defineStrategy(selector)) {
    // user has specified locator strategy directly
    case 'directly': {
        const match = selector.match(DIRECT_SELECTOR_REGEXP)
        if (!isMobile && isW3C && !W3C_SELECTOR_STRATEGIES.includes(match[1])) {
            throw new Error('InvalidSelectorStrategy') // ToDo: move error to wdio-error package
        }
        using = match[1]
        value = match[2]
        break
    }
    case 'xpath': {
        using = 'xpath'
        break
    }
    case 'id': {
        using = 'id'
        value = selector.slice(3)
        break
    }
    case 'link text': {
        using = 'link text'
        value = selector.slice(1)
        break
    }
    case 'partial link text': {
        using = 'partial link text'
        value = selector.slice(2)
        break
    }
    case '-android uiautomator': {
        using = '-android uiautomator'
        value = selector.slice(8)
        break
    }
    case '-android datamatcher': {
        using = '-android datamatcher'
        value = JSON.stringify(value)
        break
    }
    case '-ios uiautomation': {
        using = '-ios uiautomation'
        value = selector.slice(4)
        break
    }
    case 'accessibility id': {
        using = 'accessibility id'
        value = selector.slice(1)
        break
    }
    case 'class name': {
        using = 'class name'
        break
    }
    case 'tag name': {
        using = 'tag name'
        value = selector.replace(/<|>|\/|\s/g, '')
        break
    }
    case 'name': {
        if (isMobile || !isW3C) {
            using = 'name'
            value = selector.match(/^\[name=("|')([a-zA-z0-9\-_.@=[\] ']+)("|')]$/)[2]
        }
        break
    }
    case 'xpath extended': {
        using = 'xpath'
        const match = selector.match(new RegExp(XPATH_SELECTOR_REGEXP.map(rx => rx.source).join('')))
        const PREFIX_NAME = { '.': 'class', '#': 'id' }
        const conditions = []
        const [
            tag,
            prefix, name,
            attrName, attrValue,
            partial, query
        ] = match.slice(1)
 
        if (prefix) {
            conditions.push(`contains(@${PREFIX_NAME[prefix]}, "${name}")`)
        }
        if (attrName) {
            conditions.push(
                attrValue
                    ? `contains(@${attrName}, "${attrValue}")`
                    : `@${attrName}`
            )
        }
        conditions.push(
            partial ? `contains(., "${query}")` : `normalize-space() = "${query}"`
        )
        value = `.//${tag || '*'}[${conditions.join(' and ')}]`
        break
    }
    }
 
    /**
     * ensure selector strategy is supported
     */
    if (!isMobile && isW3C && !W3C_SELECTOR_STRATEGIES.includes(using)) {
        throw new Error('InvalidSelectorStrategy') // ToDo: move error to wdio-error package
    }
 
    return { using, value }
}