Skip to main content
Cypress应用

Cypress.SelectorPlayground

Selector Playground 提供了 API,允许您:

  • 更改默认的选择器策略
  • 覆盖每个元素返回的选择器

语法

Cypress.SelectorPlayground.defaults(options)
Cypress.SelectorPlayground.getSelector($el)

参数

options (Object)

包含以下任意或全部选项的对象:

选项接受类型描述
selectorPriority字符串数组确定元素选择器的优先级顺序。
onElement函数一个接收元素并应返回该元素唯一选择器字符串的函数。如果返回假值,则使用默认选择器函数。

默认选择器优先级

  1. data-cy
  2. data-test
  3. data-testid
  4. data-qa
  5. id
  6. class
  7. tag
  8. attributes
  9. 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'