首页 > 解决方案 > 调用 cy.get('body') 后我无法选择元素

问题描述

  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(...)
}

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

标签: testingconditional-statementscypress

解决方案


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

我确定您已经阅读了如何不建议在 Cypress 中进行条件测试,但考虑到这一点,这应该会让您走上有条件地检查元素是否存在的正确道路:

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.")
            }
        })
    })
})

推荐阅读