How can we design tests and rich custom command macros when we don't know what the state of the UI will be? Conditional testing is strongly advised against by the Cypress team, but sometimes you just gotta do it.
In my case, I needed to be able to delete two types of item from a list, one of which would throw a confirmation modal, and the other wouldn't. It's hard to predict which case you'll face for many tests, so we need some sort of conditional logic here.
Conditional UI testing is hard in any tool. I can't just simply issue a cy.get()
for the modal here, because it may never exist. Instead I have to insert a hard wait and the read the entire page looking for some text that I know will be in the modal header.
cy.get('body').then(($body) => {
if ($body.text().includes("The string I'm looking for")) {
// Click the confirmation, only if the modal appears
cy.contains('button', 'OK').click();
}
});
When modals do appear, they often don't even append to the DOM in a logical location. Many times, they appear at the bottom of the document, devoid of anything but styling, free from any helpful neighboring relationships. For this reason, it's often necessary to query the entire <body>
to find what you're looking for.
Doing what I've shown here is painful, and should be avoided. If you do need to do it though, this method can work in a pinch.
Top comments (0)