无法在数组中找到和 Select 项

Unable To Locate And Select Item In Array

我正在学习使用 cypress.io 并希望同时学习 JavaScript。

我目前正在寻找自动化工作的内部应用程序作为概念证明,说明为什么我们应该考虑切换到 cypress.io 而不是 Webdriver。

我当前的问题是我有一个元素集合需要循环,其中包含某个字符串,select 这个元素。

我的代码正确定位了所有元素(位于 class 处),但是当我尝试循环遍历元素以查找具有特定字符串的元素时,我遇到了麻烦。

代码如下-

//Selecting profiles
cy.get('.card')
    .each(($el) => {
        if ($el.contains() === profile) {
            cy.wrap($el).click();
        }
    })

配置文件变量被传递到此代码段所在的函数中。

我正在查看 .each 和 .contains 函数的 cypress 文档。

但是当我 运行 这段代码时,我得到异常说

TypeError: $el.contains is not a function

但是查看 cypress 文档,我可以将函数附加到 $el 对象。

.get('ul>li').each(($el, index, $list) => {
// $el is a wrapped jQuery element
if ($el.someMethod() === 'something') {
  // wrap this element so we can
  // use cypress commands on it
  cy.wrap($el).click()
} else {
  // do something else
}})

.contains() 是一个赛普拉斯函数。正如文档页面所说,$el 是一个 jQuery-wrapped 元素,而不是 Cypress-wrapped 元素,因此 .contains() 将不起作用。

也就是说,.contains() 用于筛选选择,return 将 chainer, not a boolean or a string, so this particular way of using .contains() would not work in the first place. This is a side effect of how Cypress queues its commands - see this doc page 获取更多信息。


对于你想要做的事情,我建议利用原生 jQuery 元素:

//Selecting profiles
cy.get('.card')
    .each(($el) => {
        if ($el.text() === profile) {
            cy.wrap($el).click();
        }
    })

注意:我假设 profile 是一个字符串。如果不是,则可能需要修改此代码。