I'm quite new to cypress, but I am wondering if there is some way to end a command chain conditionally? I know that conditional testing should be avoided in cypress, but I want try this out anyway.
What I've tried
I tried to solve it by passing in the chain to a custom command, but it doesn't seem to work.
Cypress.Commands.add('ifExists', { prevSubject: true }, (subject: object, element: string) => {
cy.get('body').then(($body) => {
if ($body.find(element).length) {
cy.wrap(object).end();
} else {
// something else
}
})
})
and also
Cypress.Commands.add('ifExists', { prevSubject: true }, (subject: JQuery<HTMLBodyElement>, element: string) => {
cy.wrap(subject).then(($body) => {
if ($body.find(element).length) {
return cy.wrap(subject);
} else {
return cy.wrap(subject).end();
}
})
})
And just a clarification on what I want from this command. I want to be able to add it to a chain like this:
cy.get('body > #specialThing').ifExists().then((thing) => ...)
or this:
cy.ifExists('body > #specialThing').then((thing) => ...)
All help and advice is appreciated!