Cypress.SelectorPlayground
Selector Playground 提供了 API,允许您:
- 更改默认的选择器策略
- 覆盖每个元素返回的选择器
语法
Cypress.SelectorPlayground.defaults(options)
Cypress.SelectorPlayground.getSelector($el)
参数
options (Object)
包含以下任意或全部选项的对象:
选项 | 接受类型 | 描述 |
---|---|---|
selectorPriority | 字符串数组 | 确定元素选择器的优先级顺序。 |
onElement | 函数 | 一个接收元素并应返回该元素唯一选择器字符串的函数。如果返回假值,则使用默认选择器函数。 |
默认 选择器优先级
data-cy
data-test
data-testid
data-qa
id
class
tag
attributes
nth-child
$el (Object)
您想要获取选择器值的 jQuery 元素。
示例
选择器优先级
设置选择器优先级,优先使用 ID,然后是类,最后是属性。
Cypress.SelectorPlayground.defaults({
selectorPriority: ['id', 'class', 'attributes'],
})
onElement 回调
设置一个自定义函数来确定元素的选择器。如果返回假值,则回退到默认行为。
Cypress.SelectorPlayground.defaults({
onElement: ($el) => {
const customId = $el.attr('my-custom-attr')
if (customId) {
return `[my-custom-attr=${customId}]`
}
},
})
获取选择器
根据选择器策略返回给定元素的选择器值。
例如,考虑以下 HTML 片段。
<button id="bingo" class="number3">Cup of tea</button>
使用默认选择器策略时,选 择器值将是 '#bingo'
,因为 ID 优先级高于类。
const $el = Cypress.$('button')
const selector = Cypress.SelectorPlayground.getSelector($el) // '#bingo'
使用优先考虑类的自定义选择器策略时,选择器值将是 '.number3'
。
Cypress.SelectorPlayground.defaults({
selectorPriority: ['class', 'id'],
})
const $el = Cypress.$('button')
const selector = Cypress.SelectorPlayground.getSelector($el) // '.number3'