【问题标题】:I can't select an element after calling cy.get('body')调用 cy.get('body') 后我无法选择元素
【发布时间】:2021-05-25 18:35:13
【问题描述】:
  cy.get('body'). then(body => {
      cy.wrap(body).should('have.class','.layout-header')
  }

cypress 没有找到“layout-header”类。当我这样做时,它就会起作用:

 cy.get('body'). then(body => {
      
       cy.get('.layout-header')
  }

我需要这个,因为我想使用这样的条件测试:

cy.get('body').then(($body) => {
// synchronously ask for the body's text
// and do something based on whether it includes
// another string
if ($body.text().includes('some string')) {
  // yup found it
  cy.get(...).should(...)
} else {
  // nope not here
  cy.get(...).should(...)
}

}) 你能告诉我为什么吗?谢谢

【问题讨论】:

    标签: testing conditional-statements cypress


    【解决方案1】:

    您的测试cy.wrap(body).should('have.class', '.layout-header') 的第一部分是寻找一个名为.layout-header 的类以存在于 body 元素上,而不是within body 元素的子元素.

    我相信您已经阅读了Cypress is not advised 中的条件测试方法,但考虑到这一点,这应该会让您走上正确的路径来条件检查元素是否存在:

    cy.get("body").then(body=>{
      // This will perform a document query on your body element and   
      // give you a static node list of child elements have the class '.layout-header'
      const hasClass = body[0].querySelectorAll(".layout-header")
      if(hasClass.length > 0)
      {
        //Code to execute if the class exists in the body
      }else{
        //Code to execute if the class DOES NOT exist in the body
      }
    })
    

    针对演示测试站点的工作示例

    describe("working example", ()=>{
        it("check body for elements with class name 'custom-control-label'", ()=>{
            cy.visit("https://demoqa.com/automation-practice-form")
            cy.get("body").then(body=>{
                const hasClass = body[0].querySelectorAll(".custom-control-label")
                if(hasClass.length > 0)
                {
                    cy.log(`The class 'custom-control-label' was found in the body ${hasClass.length} times.`)
                }else{
                    cy.log("The class 'custom-control-label' was NOT found in the body.")
                }
            })
        })
    })
    

    【讨论】:

    • 好的,谢谢,但是当我想选择例如 class="layout" 时,这不起作用。
      。 . .
    • @Ahmad 您介意提供更多信息吗?你说的“它不起作用”是什么意思?
    • 我的意思是当我这样写时: const hasClass = body[0].querySelectorAll(".layout") 他没有找到元素。这意味着 has.Class.length= 0 而我想要那个。
    • layout 是 body 的子子子元素
    • layout 类元素相对于主体的嵌套深度无关紧要,这应该返回所有具有layout 类的子元素。您能否先检查一下您的初始 cy.get() 命令是否返回了正确的元素,以及您要查询的类名是否正确?
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签