在我的Cypress测试中,我试图检查页面上是否存在一个元素。
如果它存在的话,做点什么,做其他的事情。我正在获取主体,然后找到元素,然后使用.find()和is检查它是否存在。(‘:visible’)
当我这样做时,isVisible始终是假的,尽管存在以下元素:
cy.get( 'body' ).then(( $body ) => {
const isVisible = $body.find( 'div[style="white-space: nowrap;"]' ).is( ':visible' );
// never executes
if ( isVisible ) {
cy.log( 'It is visible' );如果我像这样在.find()之后执行.get (),它会发现它和isVisible是真的,但是元素并不总是出现在页面上,所以这个.find()有时会失败。
cy.get( 'body' ).find( 'div[style="white-space: nowrap;"]' ).then(( $body ) => {
const isVisible = $body.is( ':visible' );
if ( isVisible ) {
cy.log( 'It is visible' );我的逻辑错了吗?有没有更好的方法来检查页面上的元素?
HTML结构:
<body style>
<div id="__next">
<div class>
<nav data-baseweb="header-navigation" role="navigation" class="ae af ag ah ai aj ak al am an ao ap aq ar as at au">
<ul class="ai av aw ax ay az b0 b1 b2 b3 b4 b5 b6 b7 b8">
<li class="b9 ay b7 az b8 b4 ba b3 b5">
<li>
<ul>
<nav>
<div style="padding:0" class="bb bc bd">
<div class="ai be bf bg bh">
<div class="ai bx bv by bi bz">
<div class="ai c0 c1 b6 c2 c3 bf b1 c4 au">
<div class="ai c5 bs bt c6 c7 c8 c9 bf">
<div class="ai bv b1 bw bg">
<h6 data-baseweb="typo-headingxsmall"> <h6>
<div class>
<button disabled class="css-jfmp5u e1g3plmq1"> <button>
<div style="white-space: nowrap;"> <div>
<button class="css-jfmp5u e1g3plmq1"> <button>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<body>发布于 2022-04-26 15:29:00
如果您正在检查DOM中元素的存在,那么在jquery中使用length属性。
cy.get('body').then(($body) => {
if ($body.find('div[style="white-space: nowrap;"]').length > 0) {
//element exists do something
} else {
//Element doesn't exists. Do Something
}
})发布于 2022-04-26 21:50:36
没有足够的信息给出确切的答案(您已经从HTML中删除了太多的细节),但是您需要cy.get()一些总是在页面上呈现的元素,但是只有在页面加载完成之后。
cy.get('body')不会这么做,因为它从一开始就在页面上,所以您的内部可见性测试会立即运行,但是内部HTML仍然在加载。
因此,假设div[class="always-rendered"]是这样一个元素,您可以使用Cypress重试,也可以执行条件检查。
cy.get('div[class="always-rendered"]').then($el => {
const isVisible = $el.find('div[style="white-space: nowrap;"]').is( ':visible' );
if (isVisible) {
console.log( 'It is visible' );不要使用cy.log()进行调试,请使用console.log()
而div[style="white-space: nowrap;"]是一个非常糟糕的选择器,可能有很多元素具有这种风格。
https://stackoverflow.com/questions/72015735
复制相似问题