In my Cypress test I'm trying to check if an element exists on the page.
If it exists, do something, else do something else. I'm getting the body then finding the element then checking if it exists using .find() and is.(':visible')
When I do it this way, isVisible is always false, despite the element existing:
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' );
If I do .find() right after .get like this, it finds it and isVisible is true, but the element is not always present on the page, so this .find() will fail sometimes.
cy.get( 'body' ).find( 'div[style="white-space: nowrap;"]' ).then(( $body ) => {
const isVisible = $body.is( ':visible' );
if ( isVisible ) {
cy.log( 'It is visible' );
Is my logic wrong? Is there a better way to check for an element on the page?
HTML Structure:
<body style>
<div id>
<div class>
<div style>
<div class>
<div class>
<div class>
<div class>
<div class>
<div class>
<div style="white-space: nowrap;"> <div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<body>
CodePudding user response:
If you are checking the presence of the element on the DOM then use the length
attribute in jquery.
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
}
})
CodePudding user response:
There's not enough info to give an exact answer (you've removed too much detail from the HTML), but you need to cy.get()
some element that always rendered on the page, but only after page loading is complete.
cy.get('body')
won't do it because it is on the page from the start, so your inner visibility test runs immediately but the inner HTML is still loading.
So presume div[]
is such an element, you can make use of Cypress retry as well as doing a conditional check.
cy.get('div[]').then($el => {
const isVisible = $el.find('div[style="white-space: nowrap;"]').is( ':visible' );
if (isVisible) {
console.log( 'It is visible' );
Do not use cy.log()
to debug, use console.log()
And div[style="white-space: nowrap;"]
is a really bad selector, there could be lots of element with that style.