testing - 调用 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(...)
}
}) 你能告诉我为什么吗?,谢谢
解决方案
测试的第一部分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.")
}
})
})
})
推荐阅读
- machine-learning - 回归模型的特征显着性检验,例如 Lasso
- c++ - 如何访问可变参数模板函数中的参数
- kubernetes - 如何将 K8s 服务同步到 K8s 外的 Consul Cluster?
- perl - 如何使用 perl 删除目录及其内容?
- ruby-on-rails - Rails 表单输入不保存,提交后变为空白
- java - JFrame actionlistener 在相同/链接的 JPanel actionlistener 之前激活
- excel - 选择单元格的通用分组(非静态)
- c++ - 如何从 cstdlib 修复 stdlib.h 的 include_next?
- google-cloud-platform - Issue to create domain mapping
- azure - AICS Test Report for Android device