I have a test in cypress typescript where my target element is dynamic and keep moving between two different pages. sometime it shows on first page and next time you run the application it display on second page. I am trying to use if/else statement to click on element on first page and if it is not available on first page then move to second page and click on the element. I have wrote the following but it keep failing my test.
Asked
Active
Viewed 76 times
-1
-
It is recommended to copy paste the code in text format to make it easier to answer. – jjhelguero Mar 16 '23 at 17:28
-
Does this answer your question? [Cypress - if then functions](https://stackoverflow.com/questions/53448012/cypress-if-then-functions) – DJSDev Mar 16 '23 at 20:37
3 Answers
3
To use an if statement inside a test, please follow this example Element-existence.
cy.get('body').then(($body) => {
// synchronously query from body
if ($body.find('a[href="/smc/11"]').length) {
cy.get('a[href="/smc/11"]').click()
} else {
cy.get('button[id="pagination-last-page"]').click()
cy.get('a[href="/smc/11"]')
.should('be.visible')
.click()
}
})
This can be flaky if the page is still loading, so you might add a check for something else on the page first, for example
// check something that is visible only after page has loaded
cy.get('button[id="pagination-last-page"]').should('be.visible')
cy.get('body').then(($body) => {
// synchronously query from body
if ($body.find('a[href="/smc/11"]').length) {
cy.get('a[href="/smc/11"]').click()
} else {
cy.get('button[id="pagination-last-page"]').click()
cy.get('a[href="/smc/11"]')
.should('be.visible')
.click()
}
})

Amy.Trigg
- 31
- 3
0
One way to check is using Cypress.dom.isVisible()
to check for the elements' visibility.
cy.get("a[href='/smc/11']")
.then($a => {
if(Cypress.dom.isVisible($a)) {
cy.wrap($a).click()
} else {
// else condition code
}
})

jjhelguero
- 2,281
- 5
- 13
0
You can use JQuery's :visible
to determine if the element is visible, and act accordingly.
cy.get('a[href="/smc/11"]').then(($el) => {
if ($el.is(':visible')) {
cy.wrap($el).click();
} else {
cy.get('button[id="pagination-last-page"]').click();
cy.get('a[href="/smc/11"]').click();
}
});

agoff
- 5,818
- 1
- 7
- 20