what is expected from the below code is get_plz_ChooseGroup
will be skipped and not trigger a test failure if the element is not visible after 5000 seconds
Login_Page_POS.get_plz_ChooseGroup({ timeout: 5000 })
.then(($element) => {
if ($element.is(":visible")) {
Login_Page_POS.chooseGroup(groupName)
} else {
cy.log("Element not visible after 5 seconds, skipping this part")
}
})
.catch(() => {
cy.log("Element not found after 5 seconds, skipping this part")
})
and :
this.plz_group_Label = "//span[contains(text(),'Please choose your group')]"
get_plz_ChooseGroup() {
return cy.xpath(this.plz_group_Label)
}
fails at .catch(() => {:
_Login_Page_POS.default.get_plz_ChooseGroup(...).then(...).catch is not a function
2
Answers
If you search Cypress docs for
.catch()
you will find that there is no such command.The
cy.xpath(this.plz_group_Label)
command fails if there is no such element in the DOM.The way to do this is by polling for the element for 5 seconds using jQuery methods, which uses CSS selectors rather than xpath selectors.
To poll you will need a recursive function/method, for example:
The invocation would be
I have to say, this is not a very good way to test – what if the element isn’t found? You will skip part of your test code, presumably it is important to run it every time you run the test.
I suggest taking a look at How to write a test which explains the Arrange-Act-Assert pattern.
Cypress has a
.then()
(see https://docs.cypress.io/api/commands/then) but the catch is that it does not have a.catch()
. You can catch test failures viaCypress.on
and you can have assertions to test the results you expect. You can still use acatch
if you want, as long as you wrap a promise around your code and use acatch
on the now-valid promise. you could use a flag inside the promise, defaulting to false and, if the Cypress stuff is executed inside the promise, then set this flag to true. Wrapping asetTimeout
with 5 seconds around it with failing the promise if the flag is still false after 5 seconds, whereas if it gets true before that, then fulfill the promise you wrapped around this.