Codehan25
Codehan25

Reputation: 3014

How to check if an element exists within the body with cypress?

I want to check whether the nextjs-portal tag appears in the body of my page and if so, then click on it.

How can I do that with cypress?

This works, but I need the if block now:

cy.get('nextjs-portal').click();

Something like

if (cy.get('nextjs-portal')) {
  cy.get('nextjs-portal').click();
}

Upvotes: 0

Views: 1307

Answers (1)

pavelsaman
pavelsaman

Reputation: 8362

You don't need any if here. If the element does not exist, cy.get('nextjs-portal') will time out and no click will happen.

If you really really need conditional testing, it can be done, but it's usually an anti-pattern:

cy
  .get('body')
  .then($body => {
    if ($body.find('.nextjs-portal').length) {
      // now you know the element was found in the DOM
    } else {
      // your element was not found in the DOM
    }
  });

Upvotes: 1

Related Questions