I’m writing Cypress End-to-End tests where I need first to check if a specific button is present on my web page (conditionnal testing).
This is what I did:
cy.get('body')
.then($body => {
if ($body.has(".myClass").length) {
//DO SOMETHING
}
})
This works fine, but when I try to select the subelement based on its attribute instead of a class, then the subelement is not found. Meaning this didn’t work:
cy.get('body')
.then($body => {
if ($body.has("div[data-cy='deleteButton']").length) {
//DO SOMETHING
}
})
I don’t understand what the problem is. Anyone a clue?
I experimented further, and it looks that even when using class, some subelements can not found. Below you see the HTML structure and the class i could use as identifier, the class I couldn’t use as identifier and the data-cy attribute I’m trying to work with:
3
Answers
You can use the
.attr
jquery method like this:That looks like the problem with conditional testing and asynchronous loading. The
if
statement might be running before the page has loaded.If you take a simplified and static version of the page
and open it in the browser, the test passes
so it’s likely the problem is due to loading delays.
Instead of
$body
, please try a static element close to that section of the page that also loads asynchronously but is not conditionalI’m guessing