jquery 函数返回布尔值以检查元素是否存在于Cypress [重复]中

bpzcxfmw  于 2023-08-04  发布在  jQuery
关注(0)|答案(2)|浏览(94)

此问题在此处已有答案

How to check for an element that may not exist using Cypress(6个答案)
22天前关闭
我怎么能写一个函数返回布尔值来检查是否存在的元素在用户界面上的柏树。
我有下面的代码,它似乎工作正常,直到我遇到一个元素,我只能得到元素使用cy.get('.I_am_selector')
当我使用函数isElementExist()时,它总是返回false,因为Cypress.$('.I_am_selector').length == 0;

export function isElementExist(selector: string): boolean {
  try {
    return Cypress.$(`.${selector}`).length > 0;
  } catch (error) {
    return false;
})

字符串

slwdgvem

slwdgvem1#

Cypress cy.get()内置了重试功能,因此如果一个元素正在加载或动画化,该命令最终会抓取该元素。
但是jQuery等价的Cypress.$(.${selector} )没有重试。您可以尝试在函数中构建一些轮询,但这需要大量的工作,为什么Cypress中没有内置cy.maybe(selector)
如果您知道存在哪些元素,Cypress测试工作得最好,有很多关于它的文档,但总是有边缘情况。
我看到的唯一方法是在这里使用How can manage the application flow, if the element xpath is not present,使用cypress-xpath插件和count()函数。

cy.xpath(`count(//${element}[@class="${selector}"])`)  // ok with async content
  .then(count => {
    const selector = count ? selector : defaultSelector;

字符串
您可能正在寻找jQuery OR Selector,它允许您在逗号后提供默认选择器。
如果DOM是这样的

<div class="pick-me">one</div>
<div class="or-me">two</div>


此测试将获取div.pick-me

cy.get('.pick-me, .or-me')            // jQuery OR selector
  .eq(0)                              // in case both match, take first
  .should('have.class', 'pick-me');   // first selector is used


但是如果DOM没有第一个类,

<div class="dont-pick-me">one</div>
<div class="or-me">two</div>


该命令将返回默认选择器

cy.get('.pick-me, .or-me')          // jQuery OR selector
  .eq(0)                            // in case both match, take first
  .should('have.class', 'or-me');   // default selector is used

vwkv1x7d

vwkv1x7d2#

此功能内置于Cypress中。尝试以下任何命令:

// These both search for if a selector matches (I am not clear on the difference)
Cypress.dom.isDom(Cypress.$(selector))
Cypress.dom.isAttached(Cypress.$(selector))

// This searches for if a selector does not match
Cypress.dom.isDetached(Cypress.$(selector))

字符串
这些都在Cypress Website上有文档记录,旨在用于自定义命令,而不是直接用于测试。

相关问题