1

The question of how to perform conditional checking in Cypress.io has been asked multiple times, but provided solutions I have found do not work:

Using Cypress.io, I wish to have a conditional to check for the following element, and if it exists then perform some action:

<a data-cy="foo"><span>ABCDE</span></a>

I tried the following conditional using Cypress.io, which works fine if element 'foo' exists:

  cy.log('check if element foo exists');
  cy.get('a[data-cy="foo"]')
      .then(($element) => {
        cy.log('element foo exists');
        if ($element.is(':visible')) {
          cy.log('element foo visible');
        }
      })

...however, it errors if element 'foo' does not:

Timed out retrying: Expected to find element: a[data-cy="foo"], but never found it.

This is expected to be conditional and not an assertion.

Thank you, much appreciate any assistance.

Jeff
  • 1,917
  • 1
  • 25
  • 43

2 Answers2

1

cy.get('a[data-cy="foo"]') already expects the element to exist, otherwise will fail, unless if you add an explicit assertion via .should. In order to check for a dynamic element, then you have to chain it from an upper(parent) element in the component tree, e.g:

    cy.get('.app__inner').then($app => {
        if (app.find('[data-cy="foo"]').is(':visible')) {
            cy.log('element foo exists');
        } else {

          cy.log('element foo not visible');
        }
    });
Alex Izbas
  • 595
  • 5
  • 8
  • I am having issues. It does not work if find(element) is not visible. ```AssertionError Timed out retrying: Expected to find element: ..., but never found it.``` – Jeff Jul 14 '20 at 01:47
  • 1
    yeah, usually all option elements are considered hidden, regardless of their selected state. So you can remove it and use `if ($app.find('[data-cy="foo"]').length) {...}` – Alex Izbas Jul 15 '20 at 13:08
  • Your latest reply using `.length` works out perfectly. **root element:** `div.content_main`, **code example:** ```cy.get('div.content_main').then($divRulesContentMain => { ... if ($divRulesContentMain.find('div.emptyState').length) { ... cy.get('div.content_main').then($divEmptyState => { ``` – Jeff Jul 24 '20 at 01:53
0

This is a simple Example. It will work for you Please Try this one:

cy.get('header').then(($a) => { 
    if ($a.text().includes('Account')) {
        cy.contains('Account')
        .click({force:true})
    } else if ($a.text().includes('Sign')) { 
        cy.contains('Sign In')
        .click({force:true})  
    } else {
        cy.get('.navUser-item--account .navUser-action').click({force:true})
    }
})
GHULAM NABI
  • 498
  • 5
  • 15