cypress:如果不存在元素xpath,如何管理应用程序流 [英] cypress: How can manage the application flow, if the element xpath is not present

查看:56
本文介绍了cypress:如果不存在元素xpath,如何管理应用程序流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况:

如果存在该元素,则我必须进行一项活动,如果不存在,则将进行另一项活动.

if the element is present, i have to do one activity and if not present will do another activity.


  cy.xpath("//div[text()= 'button').its('length').then(res=> {
 
  if (res > 0) {
    return 1;
}
else {

cy.log ("Element is not present")

    }
 }
)} '''

if element is present = Code is working fine, 
if the element xpath is not present = it try to search the element xpath (//div[text()= 'button') and throwing the error as 'Timed out retrying: Expected to find element: undefined, but never found it.'

if element is not present, Is there any way, i can handle the code ,

推荐答案

使用xpath时,您可以将xpath选择器包装为 count().

When using xpath you can (sort of) make it conditional by wrapping the xpath selector with count().

cy.xpath("count(//div[text()= 'button'])")  // ok with async content
  .then(count => {
    if (count) {

      //return 1;  // not useful, returns a "chainer"
      // ...but you can perform the required test here, e.g
      cy.xpath("//div[text()= 'button']").click()

    } else {
      cy.log('not found')
    }

  })

使用内置jQuery的较短语法可能是

The shorter syntax using built-in jQuery might be

const exists = !!Cypress.$("div:contains('button')").length

if (exists) {
  cy.xpath("//div[text()= 'button']").click()
} else {
  cy.log('not found')
}

请注意,这是对按钮"的部分匹配,其中xpath语法是完全匹配.

Note that this is a partial match to 'button', where-as the xpath syntax is an exact match.

也请注意-使用 Cypress.$ 绕过

Also note - using Cypress.$ by-passes retry-ability, so it should not be used where the text is asynchronous.

来自文档

这是从开发人员工具进行调试时 同步 查询元素的好方法.

This is a great way to synchronously query for elements when debugging from Developer Tools.

含义是页面加载后更多用于调试.

The implication is that it's more for debugging after the page has loaded.

最佳实践是尝试构造测试和应用程序数据,以使您 知道 该按钮存在.

The best practice is to try to construct the test and the app's data in such a way that you know that the button is present.

这篇关于cypress:如果不存在元素xpath,如何管理应用程序流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆